2

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?

Amanda
  • 2,013
  • 3
  • 24
  • 57
  • You can do that by using one of the IO multiplexing `select()`/`poll()`/`epoll()` functions instead of unconditionally reading from `socket_fd`.Those also give you the timeout you need ... – dragosht Feb 01 '20 at 09:05
  • Does this answer your question? [setting timeout for recv fcn of a UDP socket](https://stackoverflow.com/questions/16163260/setting-timeout-for-recv-fcn-of-a-udp-socket) – kaylum Feb 01 '20 at 09:21

1 Answers1

1

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

Julien J
  • 2,826
  • 2
  • 25
  • 28
  • What is the difference between `close` and `shutdown`? – Amanda Feb 01 '20 at 18:40
  • Generally the difference between close() andshutdown() is: close() closes the socket id for the process but the connection is still opened if another process shares this socket id. ... shutdown() breaks the connection for all processes sharing the socket id. – Julien J Feb 01 '20 at 18:43
  • Is there a way to register a callback when a timeout is being called? Is there a way to know the exit was because of a timeout or a normal exit? – Amanda Feb 01 '20 at 18:48
  • Sorry Amanda. I didn't experience that for now. I gonna answer back If I found the answers to your questions. Thank you for your interest. – Julien J Feb 01 '20 at 18:54