Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 17.  Socket Programming

Server Sockets

A TCP server socket allows multiple clients. The way this works is that the socket command creates a listening socket, and then new sockets are created when clients make connections to the server. Tcl takes care of all the details and makes this easy to use. You simply specify a port number and give the socket command a callback to execute when a client connects to your server socket. The callback is just a Tcl command. A simple example is shown below:

Example 17-2 Opening a server socket.
set listenSocket [socket -server Accept 2540]
proc Accept {newSock addr port} {
   puts "Accepted $newSock from $addr port $port"
vwait forever

The Accept command is the callback. With server sockets, Tcl adds additional arguments to the callback before it calls it. The arguments are the new socket connection, and the host and port number of the remote client. In this simple example, Accept just prints out its arguments.

The vwait command puts Tcl into its event loop so that it can do the background processing necessary to accept connections. The vwait command will wait until the forever variable is modified, which won't happen in this simple example. The key point is that Tcl processes other events (e.g., network connections and other file I/O) while it waits. If you have a Tk application (e.g., wish), then it already has an event loop to handle window system events, so you do not need to use vwait. The Tcl event loop is discussed on page 217.

Server Socket Options

By default, Tcl lets the operating system choose the network interface used for the server socket, and you simply supply the port number. If your computer has multiple interfaces, you may want to specify a particular one. Use the -myaddr option for this. The general form of the command to open server sockets is:

socket -server callback ?-myaddr address? port

The last argument to the socket command is the server's port number. For your own unofficial servers, you'll need to pick port numbers higher than 1024 to avoid conflicts with existing services. UNIX systems prevent user programs from opening server sockets with port numbers less than 1024. If you use 0 as the port number, then the operating system will pick the listening port number for you. You must use fconfigure to find out what port you have:

fconfigure $sock -sockname
=> ipaddr hostname port

      Previous section   Next section