Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
added 378 characters in body; edited body; added 292 characters in body; added 18 characters in body
Source Link
Daniel Earwicker
  • 117k
  • 38
  • 209
  • 289

Windows sockets has the select function. You pass it the socket handle and a socket to check for readability, and a timeout, and it returns telling whether the socket became readable or whether the timeout was reached.

See: http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx

Here's how to do it:

bool readyToReceive(int sock, int interval = 1) { fd_set fds; FD_ZERO(&fds); FD_SET(sock, &fds); timeval tv; tv.tv_sec = interval; tv.tv_usec = 0; return (select(sock + 1, &fds, 0, 0, &tv) == 1); } 

If it returns true, your next call to recv should return immediately with some data.

You could make this more robust by checking select for error return values and throwing exceptions in those cases. Here I just return true if it says one handle is ready to read, but that means I return false under all other circumstances, including the socket being already closed.

Windows sockets has the select function. You pass it the socket handle and a socket to check for readability, and a timeout, and it returns telling whether the socket became readable or whether the timeout was reached.

See: http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx

Windows sockets has the select function. You pass it the socket handle and a socket to check for readability, and a timeout, and it returns telling whether the socket became readable or whether the timeout was reached.

See: http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx

Here's how to do it:

bool readyToReceive(int sock, int interval = 1) { fd_set fds; FD_ZERO(&fds); FD_SET(sock, &fds); timeval tv; tv.tv_sec = interval; tv.tv_usec = 0; return (select(sock + 1, &fds, 0, 0, &tv) == 1); } 

If it returns true, your next call to recv should return immediately with some data.

You could make this more robust by checking select for error return values and throwing exceptions in those cases. Here I just return true if it says one handle is ready to read, but that means I return false under all other circumstances, including the socket being already closed.

Source Link
Daniel Earwicker
  • 117k
  • 38
  • 209
  • 289

Windows sockets has the select function. You pass it the socket handle and a socket to check for readability, and a timeout, and it returns telling whether the socket became readable or whether the timeout was reached.

See: http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx