How do I check if there is data on the queue (Sockets)?

Started by
1 comment, last by cs9arh 23 years, 9 months ago
Im using sockets in my game, and I have a TCP socket and a UDP socket. Is there any way of checking to see if there is any incoming data before I call recv() or recvfrom(), which would both block. Or am I going to have to fire off another thread and block?
Advertisement
You could use ioctl() to find out how much data you can read:
       unsigned long size = 0;   int status = 0;   status = ioctl(sock, FIONREAD, &size); // Win32 uses    ioctlsocket()   if (!status && size) do_whatever();[/source]or use select() with a timeout of zero:[source]    fd_set readfds;    struct timeval timeout;    FD_ZERO(&readfds);    FD_SET(sock, &readfds);    timeout.tv_sec = 0;    timeout.tv_usec = 0;     select(sock+1, &readfds, NULL, NULL, &timeout);    if (FD_ISSET(sock, &readfds)) do_whatever();[/source]or set your sockets to non-blocking:[source]   unsigned long val = 1;   ioctl(sock, FIONBIO, &val); // Win32 uses ioctlsocket    

You could also use non-blocking sockets and just do the recv, testing to see if the socket would have blocked or not. Look at the FIONBIO option to ioctl (or ioctlsocket for Winsock)

-Mike

This topic is closed to new replies.

Advertisement