[[Created Dec 9 2005 by [lexfiend].]] [netstrings] is a string encoding invented by D. J. Bernstein (formal definition here: [http://cr.yp.to/proto/netstrings.txt]). It's 8-bit clean, easy to implement, interoperable and "safe" (at least when used correctly). Netstrings can also be trivially nested, so the list {This is a test} can be represented as 23:4:This,2:is,1:a,4:test,, # readNetString # Purpose: Reads and returns a netstring from proc readNetString {chan} { set nslen 0 set nstr "" while {![eof $chan]} { set nschar [read $chan 1] switch -glob $nschar { [0-9] { # Next char in length - add it in set nslen [expr {$nslen * 10 + $nschar}] } : { # End of length - read in $nslen bytes set nstr [read $chan $nslen] # Check to see if we've got there set readlen [string length $nstr] if {$readlen == $nslen} { # Now we must have a trailing semicolon if {[read $chan 1] == ","} { # We're done return $nstr } else { error "Missing delimiter at end of netstring" } } else { error "Netstring length ($nslen) does not match read length ($readlen)" } } - { error "Illegal character '$nschar' in netstring length" } } } } # writeNetString ? ...? # Purpose: Writes all s to as netstrings proc writeNetString {chan args} { foreach str $args { set writelen [string length $str] puts -nonewline $chan "${writelen}:${str}," } flush $chan }