# SockServ.tcl --
#
#	Opens a server socket on 127.0.0.1, localhost. Listens on port 100. 
#	This example dumps incoming data to stdout. Run the SockClnt.tcl
#	script in a seperate process after invoking this script.
#
#	Note that a server terminated host/port pair appears not reopen on a
#	client during a given session despite reactivation of the host/port pair
#	by a server. 
#
# Copyright (c) 1996 - 1997, William Byrne
#
# See the file "license.txt" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#

# the procedure to be called after a new client connection is made
proc connect { ch addr port } {
	# display info about the new connection. Don't expect the client port to
	# be 100. It will typically be an arbitrary value determined by the client.
	puts [format "New Channel: %s %s %s" $ch $addr $port]

	# see *fconfigure* in on-line help
	fconfigure $ch -blocking 0

	# setup an event handler for incoming data. Note that we're passing the channel id.
	fileevent $ch readable "ChannelCallback $ch"
}

# the event handler for incoming data. 
proc ChannelCallback { ch } {
	global V

	# read data from the channel
	set r [read $ch]

	
	if { $r != {} } {
		# display data to stdout
		puts $r

		# determine if a server-terminating character was sent. Specific
		# to this example.
		if { [regexp {^!} $r {}] } {
			puts "read term char"
#
#			DISABLED
#
#			set V done
#
		}
	}
}
		

# Open a server socket listening to port 100
set sock [socket -server connect 100]

# wrap in exception block
if [catch {
	# display socket id to stdout
	puts $sock

	# wait forever, or until variable *V* is set.
	vwait V

} err] {
	catch {puts "$err\n$errorInfo"}
}
close $sock

