logo

.:blog archive:.

C Sockets - How to receive split messages

printable version

We all know that when we invoke a send() the kernel might decide to split the message we are sending arbitrarily.
But how does the other end behave? How can I receive a message that has been split successfully and easily?
It's relatively simple: you get a blocking recv() in a while loop, inside which you put a loop of non-blocking recv(). This way the first recv() will be waiting for something to be available in the buffer. When something is available, it receives the first part. The subsequent loop retrieves all the following parts, until the buffer is empty. Et voila'! A problem solved easily!
Code snippet:
#define MAXDATASIZE 256
int num_bytes,bytes_read,flags,new_fd;
char buf[MAXDATASIZE];
/*
... Open socket, accept connection ...
*/
while ((bytes_read=recv(new_fd, buf, MAXDATASIZE-1, 0)) > 0) {
  numbytes = bytes_read;
  flags = fcntl(new_fd, F_GETFL, 0);
  fcntl(new_fd, F_SETFL, O_NONBLOCK);
  while(bytes_read > 0) {
    bytes_read=recv(new_fd, &buf[bytes_read], MAXDATASIZE-1-bytes_read, 0);
    if (bytes_read>0) numbytes += bytes_read;
  }
  fcntl(new_fd, F_SETFL, 0);
  fcntl(new_fd, F_SETFL, flags & (~O_NONBLOCK));
  if (numbytes > 0) {
    //DO STUFF
  }
}

nitbix.com © 2006 Alan Mosca, all rights reserved.

Valid HTML 4.01 Transitional
Best viewed with a computer and a monitor. An internet connection may improve experience.
Add to Technorati Favorites