[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 978
  • Last Modified:

Socket Timeout

Hi,

i wrote a TCP Server with C++ (Linux)...

my question is how can i handle a timeout in the recv function?

as example if my server stand in the recv function and the client dont respronse for 1 minute i want to close the connection.

how can i do this?
0
woigl
Asked:
woigl
  • 3
1 Solution
 
rajeev_devinCommented:
Use select before recv.
0
 
woiglAuthor Commented:
Can you give me example source?
0
 
rajeev_devinCommented:
Something like this

int fd = -1; // This is the socket you have created.

fd_set readset;
struct timeval tv;
int ret = -1;
// Initialize the set
FD_ZERO(&readset);
FD_SET(fd, &readset);
tv.tv_sec = 1;
tv.tv_usec = 0;

ret = select (FD_SETSIZE, &readset, NULL, NULL, &tv); // Wait for one second

if (ret == 0) // Timeout
{
}
else if (ret < 0) // Some error
{
}
else
{
      // Use recv
}
0
 
itsmeandnobodyelseCommented:
FYI: select can check more than one read socket at a time. You would have to call FD_SET for any socket you want to include.

An alternative method than using select is to set the socket to non-blocking. Then, a call to recv would return immediately, normally with SOCKET_ERROR that indicates that there is nothing to read.

    // set the socket to non-blocking
    unsigned long argp = 1;
    ioctlsocket (sock, FIONBIO, &argp);

   int timeoutCounter = 0;
   int timeout            = 10;  // 10 milliseconds
   while (timeoutCounter < 1000 / timeout)            
   {
        int bytes = recv(sock, buffer, sizeof(buffer)-1,0);
        if (bytes == SOCKET_ERROR)
        {
            // nothing to read
            if (WSAGetLastError() == WSAEWOULDBLOCK)
            {
               // sleep a little while
               Sleep(timeout);  
               ++timeoutCounter;
               continue;    // try again
            }
            else
            {
                cout << "ClientThread: recv error " << WSAGetLastError() << endl;
                closesocket(sock);
                break;
             }
         }
         timeoutCounter = 0;  // reset counter
         // do something with buffer
         ...
   }

Regards, Alex
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now