Sign in to follow this  

A Blocking Function ?

This topic is 4519 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, i'm coding a regular win32 console program with c++ I'm using winsock and connecting to sockets..sending data..and then receiving data..the problem is..sometimes it sits forever on recv...for ever...is there a simple way (like without multi-threading) that I can make it time-out after like 60 seconds or something? Can someone show me the code required to do this maybe? I have this currently..
int i = send(sockfd, request.c_str(), request.length(), 0);
	
char buffer[1000];
i = recv(sockfd, buffer, 1000, 0);

Share this post


Link to post
Share on other sites
Instead of calling recv() right away you can call select() with a timeout of 60 seconds. Then after select() has returned then you can call recv() if the read flag is set for the socket.

Share this post


Link to post
Share on other sites
Thanks SiCrane..

So I have code like this now..

int i = send(sockfd, request.c_str(), request.length(), 0);
char buffer[1000];
//timeout structure
timeval timeout;
timeout.tv_sec = 60;
//set of sockets
fd_set set;
set.fd_count = 1;
set.fd_array[0] = sockfd;
if (select(0, &set, 0, 0, &timeout) == 0)
cout << "timeout occured";
else
i = recv(sockfd, buffer 1000, 0);


I know it's sloppy..but will that get the job done? I would test this out..but my error occurs very seldom and I can never spot where it does it

Share this post


Link to post
Share on other sites
You really shouldn't be touching the members of fd_set directly like that. The definition of fd_set and the internal details of how it works varies quite widely between OS's. Use the FD_SET, FD_CLR, FD_ZERO, FD_ISSET macros instead.

MSDN describes them in it's entry for select.

Share this post


Link to post
Share on other sites

This topic is 4519 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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