Subject: Re: socket in TCL - DN [1]


Joel Saunier <jsaunier@my-deja.com> - 28 Jun 2000 - comp.lang.tcl

 In article <3959783f$1@newsgate.hknet.com>,
   "Liu  Tak Sun" <sunliu@imail.com> wrote:
 > How can I set up a server socket and client socket with async. events
 > handiling with TCL in a same machine?

 A similar question was posted few days ago in fr.comp.lang.tcl.
 Below are 2 files sockserver.tcl and sockclient.tcl. The last one
 is not very usefull, and must be use in a (or 2) terminal
 interactively (by using the chat proc). You can try with 2 clients
 simultaneously, and one server. The server will loop until there is
 no more channel open with a client. Obviously, a real server will
 loop until the end of time :-).

 Hope it helps,

 Joël

 ------------------------------------------------

 sockclient.tcl:
 #####
 set port 5555

 set sock [ socket localhost $port ]

 proc chat { msg } {
    global sock port

    gets $sock line
    puts stdout "CLIENT: \"$line\" come from $port"
    flush stdout

    puts $sock $msg
    flush $sock

    return ""
 }
 #####

 sockserver.tcl:
 #####
 set port 5555

 proc chat { channel client port } {
    global endLoop

    if { [ eof $channel ] != 0 } then {

       puts stdout "SERVER: closing connection from
            $client, port $port, channel $channel"
       flush stdout

       catch { close $channel }
       set index [ lsearch $endLoop $channel ]
       set endLoop [ lreplace $endLoop $index $index ]

    } else {

       catch { gets $channel line }

       puts stdout "SERVER: \"$line\" come from $client/$port"
       flush stdout

       if { "$line" != "" } then {
          puts $channel "Hey $client/$port, you said $line!"
          flush $channel
       }
    }
 }

 proc connect { channel clientAddress clientPort } {
    global endLoop

    puts stdout "SERVER: openning connection from
       $clientAddress, port $clientPort, channel $channel"
    flush stdout

    puts $channel \
       "Hello $clientAddress/$clientPort, please to meet you!"
    flush $channel

    fileevent $channel readable \
      "chat $channel $clientAddress $clientPort"
    fconfigure $channel -blocking 0

    lappend endLoop $channel

    return ""
 }

 set endLoop dummy
 set sock [ socket -server connect $port ]

 while { [ llength $endLoop ] != 0 } {
    if { "$endLoop" == "dummy" } then { set endLoop {} }
    vwait endLoop
 }
 #####

 Sent via Deja.com http://www.deja.com/
 Before you buy.

Last modified
2000-07-20

(195.108.246.52)

Note: you are looking at
the snapshot of an old wiki
- much of this information
is likely to be very outdated