C
C
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 C Downloads
#include <C_CkSocket.h>
void ChilkatSample(void)
{
BOOL success;
HCkSocket socket;
BOOL bTls;
int maxWaitMs;
int messageLength;
success = FALSE;
socket = CkSocket_Create();
// Connect to the server using TLS.
bTls = TRUE;
maxWaitMs = 5000;
success = CkSocket_Connect(socket,"example.com",5000,bTls,maxWaitMs);
if (success == FALSE) {
printf("%s\n",CkSocket_lastErrorText(socket));
CkSocket_Dispose(socket);
return;
}
// 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 = CkSocket_ReceiveCount(socket);
if (messageLength < 0) {
printf("%s\n",CkSocket_lastErrorText(socket));
CkSocket_Dispose(socket);
return;
}
printf("The peer will send %d bytes.\n",messageLength);
CkSocket_Dispose(socket);
}