Network Programming with Windows Sockets : A Socket Message Receive Function
One common method is to create a message
header with a length field, followed by the message itself, and we’ll
use message headers in the following examples. Later examples use a
different technique, end-of-string null characters, to mark message
boundaries. Fixed-length messages provide yet another solution.
The following function, ReceiveMessage, receives message length headers and message bodies. The SendMessage function is similar.
Notice that the message is received in two parts: the header and the contents. The user-defined MESSAGE type with a 4-byte message length header is:
typedef struct {
LONG32 msgLen;/* Message length, excluding this field */
BYTE record [MAX_MSG_LEN];
} MESSAGE;Even the 4-byte header requires repetitive recv calls to ensure that it is read in its entirety because recv is not atomic.
Note
The message length variables are fixed-precision LONG32 type to remind readers that the length, which is included in messages that may be transferred to and from programs written in other languages (such as Java) or running on other machines, where long integers may be 64 bits, will have a well-defined, unambiguous length.
DWORD ReceiveMessage (MESSAGE *pMsg, SOCKET sd)
{
/* A message has a 4-byte length field, followed
by the message contents. */
DWORD disconnect = 0;
LONG32 nRemainRecv, nXfer;
LPBYTE pBuffer;
/* Read message. */
/* First the length header, then contents. */
nRemainRecv = 4; /* Header field length. */
pBuffer = (LPBYTE) pMsg; /* recv may not */
/* Receive the header. */
while (nRemainRecv > 0 && !disconnect) {
nXfer = recv (sd, pBuffer, nRemainRecv, 0);
disconnect = (nXfer == 0);
nRemainRecv -=nXfer; pBuffer += nXfer;
}
/* Read the message contents. */
nRemainRecv = pMsg->msgLen;
/* Exclude buffer overflow */
nRemainRecv = min(nRemainRecv, MAX_RQRS_LEN);
while (nRemainRecv > 0 && !disconnect) {
nXfer = recv (sd, pBuffer, nRemainRecv, 0);
disconnect = (nXfer == 0);
nRemainRecv -=nXfer; pBuffer += nXfer;
}
return disconnect;
}