Version 2 of A little client-server example

Updated 2006-08-10 12:45:55

Richard Suchenwirth 2006-02-28 - The following very simple script can act as either the server or the client of a socket connection:

  • When called with "server" as first argument, it listens on the given port. Lines coming in are evaluated, and the result is sent back
  • Otherwise, the script is a client: takes lines from stdin, sends them to the server, displays the result

 set host localhost
 set port 9900

 if {[lindex $argv 0] eq "server"} {
    puts "Server started..."
    socket -server server $port
 } else {
    set chan [socket $host $port]
    fconfigure $chan -buffering line
    fileevent $chan readable [list client'read $chan]
    fileevent stdin readable [list client'send $chan]
 }

#-----------------------------------------------------

 proc server {chan addr port} {
    fconfigure $chan -buffering line -blocking 0
    while {[gets $chan line]>=0} {
        catch $line res
        puts $line->$res ;# local logging
        puts $chan $res
    }
    close $chan
 }

#------------------------------------------------------

 proc client'read chan {
    if {[eof $chan]} {close $chan; exit}
    gets $chan line
    puts <-$line
 }
 proc client'send chan {
    gets stdin line
    puts $chan $line
 }

#------------------------------------------------------

 vwait forever

See also:


Category Example - Arts and crafts of Tcl-Tk programming