ZetCode

Tcl networking

last modified November 24, 2026 Tcl 8.6

Tcl treats a network connection as a channel, the same kind of object that open returns for a file. Once a socket is connected you read it with gets, write it with puts, and dispose of it with close. The interesting part is therefore not the I/O but the event loop that decides when a channel is ready.

This article builds a TCP client, a TCP server and a small HTTP client. Every example uses a local address, so nothing here needs an internet connection. The open and gets pages describe the channel commands that sockets reuse.

The socket command

With a host and a port, socket opens a client connection and returns a channel. With the -server option it creates a listening socket instead, and Tcl calls the given command with three arguments, the new channel, the peer address and the peer port, once for every accepted connection.

The first script uses both forms in one file. The server writes a line as soon as a client arrives, and the client reads it after the event loop has had a chance to accept the connection.

socket_intro.tcl
proc hello {chan addr port} {
    puts $chan "Hello there!"
    flush $chan
    close $chan
    set ::done 1
}

set server [socket -server hello 4242]
set client [socket 127.0.0.1 4242]
vwait ::done
puts "client read: [gets $client]"
close $client
close $server

The hello procedure writes one line, flushes the buffer and closes the channel. The client channel exists immediately, but the accept callback runs only when Tcl processes events. That is the job of vwait: it runs the event loop until the variable done is written inside the callback. Without it the script would print nothing.

$ tclsh socket_intro.tcl
client read: Hello there!

A TCP client

A client connects to a known address, sends a request line and reads one reply line. The next script does that against port 4242 on the local machine.

client.tcl
set host 127.0.0.1
set port 4242

set chan [socket $host $port]
puts "sending: ping"
puts $chan "ping"
flush $chan

puts "reply: [gets $chan]"
close $chan

socket returns a channel open for both reading and writing. puts writes a line and flush pushes it out; without the flush the line could sit in the buffer. gets with a channel argument reads one line and returns -1 at end of file. The script is meant to run beside the echo server of the next section.

$ tclsh client.tcl
sending: ping
reply: echo: ping

A TCP server with socket -server and accept

A server does not call accept directly. It registers a callback with socket -server and lets the event loop deliver connections. The callback runs at the global level and must deal with each channel quickly: while it blocks, no other client is served.

server.tcl
proc handle {chan addr port} {
    puts "client connected from $addr"
    if {[gets $chan line] >= 0} {
        puts "received: $line"
        puts $chan "echo: $line"
        flush $chan
    }
    close $chan
    set ::done 1
}

set server [socket -server handle 4242]
puts "echo server listening on port 4242"
vwait ::done
close $server
puts "server stopped"

The channel passed to handle is an ordinary connected socket, so gets works as in the client. The script reads one request line, writes the answer, flushes, and closes the channel. Setting done ends the vwait, and the listening socket is closed before the interpreter exits. The captured run had the client from the previous section send its ping to this server.

$ tclsh server.tcl
echo server listening on port 4242
client connected from 127.0.0.1
received: ping
server stopped

Finding the server port

Hard-coding a port works for a test, but it fails when the port is taken, and ports below 1024 need root privileges. Passing 0 asks the operating system to choose a free port. The program then reads the local end of the channel with fconfigure $chan -sockname.

The value of -sockname is a list. Its layout depends on the Tcl build and on the address families in use: an IPv6-capable build may return the IPv4 address, a host name and the port, followed by the same triple for IPv6. The helper below returns the first field that looks like an integer instead of hard-coding an index.

port.tcl
proc port_of {chan} {
    foreach field [fconfigure $chan -sockname] {
        if {[string is integer -strict $field]} {
            return $field
        }
    }
    return ""
}

proc seen {chan addr port} {
    puts "client connected from port $port"
    close $chan
    set ::done 1
}

set server [socket -server seen 0]
set port [port_of $server]
puts "server is listening on port $port"

set client [socket 127.0.0.1 $port]
puts "client uses local port [port_of $client]"
vwait ::done
close $client
close $server

port_of walks the socket name and returns the first integer, which is the port for both the listening socket and the connected client. The server prints the port chosen by the system, the client shows its own ephemeral port, and the callback confirms that both describe one connection. The numbers change on every run.

$ tclsh port.tcl
server is listening on port 43289
client uses local port 45645
client connected from port 45645

Non-blocking I/O with fileevent

A blocking gets stops the whole interpreter until a line arrives, which freezes a GUI and stalls a server. The remedy is fconfigure $chan -blocking 0 plus fileevent: Tcl calls the registered handler whenever the channel has data and the rest of the program keeps running.

nonblocking.tcl
set messages 0
set clients {}

proc accept {chan addr port} {
    fconfigure $chan -blocking 0 -buffering line
    fileevent $chan readable [list receive $chan]
}

proc receive {chan} {
    if {[gets $chan line] < 0} {
        if {[eof $chan]} {
            close $chan
        }
        return
    }
    puts "server got: $line"
    puts $chan "ack: $line"
    incr ::messages
    if {$::messages == 2} {
        set ::done 1
    }
}

set server [socket -server accept 4242]
foreach msg {alpha beta} {
    set c [socket 127.0.0.1 4242]
    fconfigure $c -buffering line
    puts $c $msg
    lappend clients $c
}
vwait ::done
foreach c $clients {
    puts "client read: [gets $c]"
    close $c
}
close $server

Each accepted channel gets -buffering line and its own readable handler. A gets result of -1 means that no complete line is available yet, and eof tells whether the peer has closed the connection. After two requests the script stops the event loop and reads the replies, which are already buffered in the client channels.

$ tclsh nonblocking.tcl
server got: alpha
server got: beta
client read: ack: alpha
client read: ack: beta

The http package and http::geturl

HTTP is a text protocol on top of TCP, and Tcl ships with a client for it in the http package. http::geturl performs a request, waits for the response, and returns a token holding the result. The token is queried with http::status, http::ncode, http::data and http::meta, and released with http::cleanup.

The script below answers its own request with a tiny HTTP server written with socket -server, so the example stays self-contained and shows what the client receives on the wire.

http_intro.tcl
proc respond {chan addr port} {
    fconfigure $chan -blocking 0 -buffering line
    fileevent $chan readable [list read_request $chan]
}

proc read_request {chan} {
    if {[gets $chan line] < 0} {
        if {[eof $chan]} {
            close $chan
        }
        return
    }
    if {![info exists ::request]} {
        set ::request [string trim $line]
        puts "request: $::request"
    }
    if {[string trim $line] eq ""} {
        puts $chan "HTTP/1.0 200 OK"
        puts $chan "Content-Type: text/plain"
        puts $chan "Content-Length: 12"
        puts $chan ""
        puts -nonewline $chan "Hello there\n"
        flush $chan
        close $chan
        set ::done 1
    }
}

set server [socket -server respond 8080]
package require http
set token [http::geturl http://127.0.0.1:8080/]
puts "status: [http::status $token]"
puts "code:   [http::ncode $token]"
puts "body:   [string trim [http::data $token]]"
http::cleanup $token
close $server

http::geturl connects, sends GET / HTTP/1.1 and runs the event loop while it waits, which gives the local server a chance to accept the connection and read the request. The reply has a status line, two headers and a body; Content-Length tells the client where the body ends.

$ tclsh http_intro.tcl
request: GET / HTTP/1.1
status: ok
code:   200
body:   Hello there

A small HTTP client against a local test server

A useful client takes the URL from the command line, sets a timeout, and prints the interesting parts of the response. This one defaults to a file served by a local test server. To reproduce the run, create a directory with a file named notes.txt and start python3 -m http.server 8000 --bind 127.0.0.1 in it.

http_client.tcl
package require http

set url [expr {$argc ? [lindex $argv 0] : "http://127.0.0.1:8000/notes.txt"}]
set token [http::geturl $url -timeout 5000]

puts "url:    $url"
puts "status: [http::status $token]"
puts "code:   [http::ncode $token]"

foreach {key value} [http::meta $token] {
    switch -- [string tolower $key] {
        content-type   {puts "type:   $value"}
        content-length {puts "length: $value"}
    }
}

puts "--- body ---"
puts [string trimright [http::data $token]]
http::cleanup $token

-timeout is given in milliseconds and covers the whole transaction. http::meta returns a flat list of header names and values, so the script walks it in pairs and lower-cases each name. The body keeps its trailing newline, which string trimright removes. Calling http::cleanup frees the token.

$ tclsh http_client.tcl
url:    http://127.0.0.1:8000/notes.txt
status: ok
code:   200
type:   text/plain
length: 38
--- body ---
First line of the notes.
Second line.

Error handling and timeouts

Network failures are ordinary Tcl errors. A refused connection makes socket raise an error, and catch turns it into a message. The HTTP layer behaves slightly differently: a failed connection also raises an error, but an expired -timeout returns a token whose status is timeout. Both paths deserve a check.

http_errors.tcl
if {[catch {socket 127.0.0.1 9} chan]} {
    puts "socket failed: $chan"
}

package require http
if {[catch {http::geturl http://127.0.0.1:9/ -timeout 1000} token]} {
    puts "geturl failed: $token"
}

proc silent {chan addr port} {
    fconfigure $chan -blocking 0
    fileevent $chan readable {}
    set ::silent $chan
}

set server [socket -server silent 8099]
set token [http::geturl http://127.0.0.1:8099/ -timeout 700]
puts "slow server status: [http::status $token]"
http::cleanup $token
close $::silent
close $server

The first block connects to port 9, the traditional discard port, which is closed here. The second block makes the same attempt through the HTTP package. The third starts a server that accepts the connection and never replies; after 700 milliseconds http::geturl gives up and the token reports timeout. The token is cleaned up and both channels are closed.

$ tclsh http_errors.tcl
socket failed: couldn't open socket: connection refused
geturl failed: connect failed connection refused
slow server status: timeout

Source

The Tcl 8.6 manual documents socket, fconfigure and fileevent, the three commands this article builds on. The HTTP package has its own documentation in Tcllib.

This article showed how Tcl represents a connection as a channel, how to write a client and a server with socket, how to find the port of a listening socket, how to keep a server responsive with fileevent, and how to fetch a URL with the http package. Continue with the Tcl after command to see how timers cooperate with the same event loop, or read the http package page for cookies, POST requests and proxies.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.