#!/usr/local/bin/wish

global connect_info
button .fred -text quit -command exit
pack append . .fred {top fillx filly}

proc check_command {list} {
	foreach name $list {
		if {[info commands $name] != $name} {
			puts stderr "You do not have the \"$name\" command installed"
			exit
		}
	}
}

check_command {connect accept filehandler shutdown}

proc accept_conn {type fid} {
# Accept a connection, receive 1 line, print it out, close the connection
	global connect_info
	set new_conn [accept $fid]
	set host [lindex $connect_info($new_conn) 0]
	set port [lindex $connect_info($new_conn) 1]
	puts stdout "Accepted new conn from host '$host', port $port ... it said:"
	puts stdout [gets $new_conn]
	shutdown $new_conn read
	# Don't allow any more reads... not really necessary here... just a demo
	puts $new_conn "Thank you for that wonderful contribution"
	close $new_conn
	puts stdout "Connection closed"
}

# Setup server on system allocated port with wildcard incoming address matching
set inet_server [connect -server "" ""] 
# Get the port number
set port_num $connect_info($inet_server)

puts stdout "I got port $port_num, try 'telnet localhost $port_num'"
puts stdout "It will accept one line and then close the connection"

# select will trigger when accept will not block if we want reads.
filehandler $inet_server r accept_conn

puts stdout ""

# Connect to a port on this machine and read something

if {[catch "connect localhost daytime" daytime] != 0} {
	puts stdout "Cannot connect to 'daytime' socket on your machine!"
	puts stdout "$daytime"
} else {
	puts stdout "Daytime on your machine is: [read $daytime]"
	close $daytime
}

# Example UNIX domain server socket
# if {[catch "connect -server /home/tym/.socket" unix_server] != 0} {
#    puts stdout "Couldn't open socket: $unix_server"
# } else {
#    filehandler $unix_server r accept_conn
# }
#
# Example client
# if {[catch "connect /home/tym/.socket" unix_client] != 0} {
#    puts stdout "Couldn't connect: $unix_client"
# } else {
#    puts $unix_client "hello there"
#    ...
# }
