#!/bin/sh
#-*- tcl -*- \
exec tclsh "$0" "$@"
# -----------------------------------

proc sxGetConnection { sock clientIP clientPort } {
    fileevent $sock readable "sxReadLine $sock"
}

proc sxReadLine {sock} {
    global dummy

    if {[gets $sock msg] < 0} {
	catch {close $sock}
	set dummy 1
	return
    }
    puts $msg
}

set l [llength $argv]
if { $l > 1 } {
    puts "Usage: sxEcho [portNumber]"
    puts " - default port is 8010 "
    exit
}

set port 8010
if {$l} {
    set port $l
}

while { 1 } {
    set err [catch { set sock [socket -server sxGetConnection $port] } msg]
    if { $err } {
	if { $msg == "couldn't open socket: address already in use"} {
	    incr port
	} else {
	    puts $msg
	    exit
	}
    } else {
	break
    }
}
puts "# PORT $port"
vwait dummy
