Sign in to follow this  

how to make recv() not block program

Recommended Posts

I know three way:

1. Use multithreading, one thread for network management and the other for the program.

2. If you use Windows, you can check MSDN for WSA function (WSAAccept(), WSAAsynchSelect(), WSAConnect(), WSARecv(), WSASend()) but I never really learned them.

3. Easiest way for you, check ioctlsocket()

unsigned long result = 0;
ioctlsocket( mySocket, FIONREAD, &result);
If result > 0 : Data waiting on buffer to do recv(), else continu with program.

Share this post

Link to post
Share on other sites
and here is a 4th way : the select() function
using the select you can put a timeout on the sockets
for recv or read data
syntax would be

struct timeval Timeout;
fd_set readfds;

readfds.fd_count = 1;
readfds.fd_array[0] = s;
Timeout.tv_sec = timeout;
Timeout.tv_usec = 0;

return(select(1, &readfds, NULL, NULL, &Timeout));

s is the socket , if timeout occurs then 0 will be returned and if data is waiting then the number of sockets waiting for operation will be returned.for more information check out the msdn.

if you are writing gui applications then the best option would be asynchronous more at

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this