Please note: the platform is Windows, not Linux.
I have a blocking TCP client socket. After connecting to the remote server, I set a read timeout (as the remote server is not stable, the network condition is bad) and then receive data.
Sometimes, the recv()
function never returns and my program is dead.
The code looks like this:
// set timeout
{
int millisec = 1000;
if(setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, (char*)&millisec, sizeof(int))) {
MessageBox(0, "setsockopt fail", "", 0);
}
}
unsigned begin_t = time(0);
int r = recv(sock_, ptr, static_cast<int>(size), 0);
unsigned end_t = time(0);
if(end_t - begin_t > 2) {
MessageBox(0, "over 2 sec", "", 0); // This MessageBox popups some time
}
I set the socket timeout to 1 second right before the recv()
function. In theory, the recv()
will never take more than 1 second. But sometimes, it still takes over 3 seconds, then the MessageBox appears.
Why is the timeout not working sometimes?