Amanda
Amanda

Reputation: 2153

Exiting the recv loop after a fixed timeout

I am using recv to receive a message on the socket from the server.

size_t b_received = 0;
char headers[2048];
while ((b_received = recv(socket_fd,
                              &headers[pos],
                              sizeof(headers) - pos - 1, 0)) > 0) {
    pos += b_received;
}

Sometimes, the server takes too long to send a message and my program is stuck and waiting for the next message.

Is there a way I could just end this loop if the server does not send me the next message after 5 seconds?

Upvotes: 3

Views: 742

Answers (1)

Born Ready
Born Ready

Reputation: 3496

You can use the setsockopt function to set a timeout on receive operations:

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Try this to stop the socket :

#include <sys/socket.h>

int shutdown(int socket, int how);

More information here

Upvotes: 2

Related Questions