PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkSocket.pb"
Procedure ChilkatExample()
success.i = 0
socket.i = CkSocket::ckCreate()
If socket.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Connect to the server using TLS.
bTls.i = 1
maxWaitMs.i = 5000
success = CkSocket::ckConnect(socket,"example.com",5000,bTls,maxWaitMs)
If success = 0
Debug CkSocket::ckLastErrorText(socket)
CkSocket::ckDispose(socket)
ProcedureReturn
EndIf
; Read a four-byte length prefix as a signed 32-bit integer (network byte order by default). A
; return value of -1 indicates failure.
messageLength.i = CkSocket::ckReceiveCount(socket)
If messageLength < 0
Debug CkSocket::ckLastErrorText(socket)
CkSocket::ckDispose(socket)
ProcedureReturn
EndIf
Debug "The peer will send " + Str(messageLength) + " bytes."
CkSocket::ckDispose(socket)
ProcedureReturn
EndProcedure