Version 15 of socket

Updated 2003-07-13 15:37:18

socket - Open a TCP network connection

 socket ?options? host port
 socket -server command ?options? port  

This command opens a network socket and returns a channel identifier that may be used in future invocations of commands like read, puts and flush. At present only the TCP network protocol is supported; future releases may include support for additional protocols like UDP and IPX. The socket command may be used to open either the client or server side of a connection, depending on whether the -server switch is specified. See also the official documentation at http://www.purl.org/tcl/home/man/tcl8.4/TclCmd/socket.htm

Server sockets can only accept incoming connections when Tcl has an event loop running. All sockets use the system encoding by default; this is probably not what you want, but it is up to the protocol to define or negotiate something more suitable.


Cameron Laird wrote in the comp.lang.tcl newsgroup:

The most widely-used solution (for ensuring only a single instance of an app is running on one machine), I think, is to set up a do-nothing networking service. Have your application

  socket -server ... 5678

when it first starts. If it's unable to do so because another service is already on 5678, take that as a previous instance of the application. Otherwise, continue. For an implementation, see How do I manage lock files in a cross platform manner in Tcl

Notice this approach is reasonably portable.

CL himself notes, somewhat later, that this is a bit "tricky", and not on the main stream of socket use; it's really socket's contribution to the theme of singleton applications.


Sockets are also one way on How can Tcl programs on two different machines communicate. JH writes on sockets in http://aspn.activestate.com/ASPN/Cookbook/Tcl/Recipe/65436 .

More possibilities are listed in the Inventory of IPC methods. Yet another example of socket service appears in http://moogy.unstable.org:8080/simple.sockets.tar.gz .


One little-known corner of TCP/IP is "port 0 networking".


Several challenges in effective network programming have to do with DNS pragmatics. DKF wrote, "numeric addresses are never resolved on socket creation on Unix, but they *are* on Windows (but I do not know if it is *really* doing it, as that depends on the Winsock implementation)."


One question that seems to arise often is about how to send a file through a socket connection.


As of 8.5, there's apparently no clean socket introspection. Socket handles do show up in "file channels", though, so, as long as one is willing to match on 'sock*', the answer is computable.


Tcl syntax help - Arts and crafts of Tcl-Tk programming - Category Command