Here's a little example for reading from a nonblocking stream socket. (untested)
Code:
unsigned int bytes_read = 0;
int ret;
char buf[MESSAGE_LEN];
while(bytes_read < MESSAGE_LEN) {
ret = recv(filedes, buf + bytes_read , MESSAGE_LEN - bytes_read, MSG_DONTWAIT);
if (ret == EAGAIN)
do_something_else_for_a_while();
else if (ret < 0)
err(EXIT_FAILURE, "recv");
else if (ret == 0)
errx(EXIT_FAILURE, "client closed the connection. how rude.");
else {
bytes_read += ret;
}
}
do_something_with_the_message(buf);
You see that I make the assumption that your messages have a fixed length of MESSAGE_LEN. If they don't, you need to decide for yourself when you're at the end of one.
Of course, the key to this example is do_something_else_for_a_while(). If you actually need to use nonblocking sockets, it's because you want to do something else instead of just sleeping until more data comes in. In my example, this is the function that does that other stuff. If you don't have other stuff to do, you should not be using nonblocking sockets.