Version 5 of Automatic Reconnect Client Sockets

Updated 2004-09-11 06:02:02

Scott Nichols I've been working on a Tcl network client for a while and have always wanted the client to be able to automatically reconnect to the server if the connection was lost. After much trial and error I finally was able to get it working they I wanted and decided to share the code. The sample code below will try to reconnect to the server every 10 seconds when there is a problem. I am very happy with it. The auto-reconnect saves the end user some frustration and troubleshooting, and also protects from network hickups. This sample code also show how to configure a client socket for nonblocking operation and also configure tdom's expat parser for situations when the large XML document may be truncated during the read and the remainder of the document arrive during the next socket read. Comments are welcome.

 package require tdom
 set ::host someserver
 set ::port someport

 # Event Driven. Called everytime XML data comes in over the socket.
 proc SockListener {dataRead} {
    if { [eof $::sock] || [catch {$::parser parse [read $dataRead]}]} {
        puts "Socket read error, trying to reconnect in 10s"
        close $::sock
        after 10000 {EventPubConnect}
    }
 }

 # Connect to the XML server
 proc EventPubConnect { } {

    if { [catch {

        # Connect to the eventpub socket
        set ::sock [socket $::host $::port]

        # Configure the socket
        set fcon [fconfigure $::sock -buffering full -buffersize 64000 -blocking false]

        # Setup the receiving socket proc
        fileevent $::sock r [list SockListener $::sock]

        set ::parser [expat] 

        $::parser configure -final 0 -elementstartcommand HandleStart -elementendcommand HandleEnd

        puts "Connected to EventPub socket $::host:$::port"

    } errorString] } {
        log "proc EventPubConnect ERROR: \"$errorString\""
        after 10000 {EventPubConnect}
    }

 }
 EventPubConnect