Sample code for 30+ languages & platforms
Tcl

Receive a 4-byte Length Prefix from a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.

Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

set socket [new_CkSocket]

#  Connect to the server using TLS.
set bTls 1
set maxWaitMs 5000
set success [CkSocket_Connect $socket "example.com" 5000 $bTls $maxWaitMs]
if {$success == 0} then {
    puts [CkSocket_lastErrorText $socket]
    delete_CkSocket $socket
    exit
}

#  Read a four-byte length prefix as a signed 32-bit integer (network byte order by default).  A
#  return value of -1 indicates failure.
set messageLength [CkSocket_ReceiveCount $socket]
if {$messageLength < 0} then {
    puts [CkSocket_lastErrorText $socket]
    delete_CkSocket $socket
    exit
}

puts "The peer will send $messageLength bytes."

delete_CkSocket $socket