aj3423
aj3423

Reputation: 2561

timeout for blocking TCP socket not working

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?

Upvotes: 0

Views: 1433

Answers (1)

Drake Wu
Drake Wu

Reputation: 7170

SO_RCVTIMEO is no supported in a blocking socket.

If a blocking receive call times out, the connection is in an indeterminate state and should be closed. If the socket is created using the WSASocket function, then the dwFlags parameter must have the WSA_FLAG_OVERLAPPED attribute set for the timeout to function properly. Otherwise the timeout never takes effect.

Using the WSASocket with WSA_FLAG_OVERLAPPED. Or socket()(default for WSA_FLAG_OVERLAPPED mode)

Upvotes: 1

Related Questions