Updated 2014-08-16 12:45:55 by aspect

MC 14 Oct 2004: Tcl's socket command and non-blocking I/O makes it very easy to do all sorts of fun network things.

Here is an example to proxy/forward in just a few lines of code. I wrote this during the intro to DRH's SQLite talk at the Eleventh Annual Tcl/Tk Conference, since some router somewhere between the hotel and mini.net wasn't routing properly.
set host mini.net
set port 80
set self 166.70.107.100 

proc accept {sock addr p} {
    global host port
    set conn [socket -async $host $port]
    fconfigure $sock -translation binary -buffering none -blocking 0
    fconfigure $conn -translation binary -buffering none -blocking 0
    fileevent  $conn readable [list xfer $conn $sock]
    fileevent  $sock readable [list xfer $sock $conn]
}

proc xfer {from to} {
    if {([eof $from] || [eof $to]) || 
       ([catch {read $from} data] || [catch {puts -nonewline $to $data}])} {
        catch {close $from}
        catch {close $to}
    } 
} 

set server [socket -server accept -myaddr $self 80]
vwait forever

vkvalli: A bandwidth throttling proxy based on this.

Category Networking