title: How to diagnose "random" winsock failures
body: <p>I have winsock2 application, running Windows on both ends.  MSVC++ 2017 is my development environment. Without getting too much into the details, the two ends of it (both written by me) send small messages back and forth.  Both ends run as a Windows service, and the connection is meant to stay running for hours or days.  The problem is that on one end of it (call it machine A), after running normally for an hour or more, the connection seems to fail.  Machine A sends a message to machine B, which is received, then machine B sends a response back.  Machine A has the socket in non-blocking mode, so it goes into a loop of calling recv() until data shows up.  If it gets WSAEWOULDBLOCK, it checks to see if a timeout interval has occurred, if not, loops back to the Recv(). The error happens because the timeout value (3 minutes) has passed.  There is no way that the data could have been delayed that long, something has been hosed.  A subsequent send() from machine A results in error 10054, connection reset.</p>
  
  <p>As I said, this can run for hours with no problems.  Other times I've seen it fail after 45 minutes or so. Both machines are configured not to go into power save mode or anything like that.  Can someone suggest how I would go about diagnosing this problem?</p>
  
  <p>Update: sample code.  The goal is to wait until a buffer of a certain length (tlen) has been received, and to allow the routine to time out if something has gone wrong:</p>
  
  <pre><code>while (TRUE) {
     Sleep(1);
     iret = recv(isocket, s, rlen, 0);
     err = WSAGetLastError();
     if (iret == SOCKET_ERROR) {
        if (err == WSAEWOULDBLOCK) {
          time(&amp;tcur);
          if (tcur &gt; tend) {
            com_Log("Timeout on recv 1");
            return(FALSE);
          }
          continue;
        }
        com_Log("Error on recv, error=%lu", err);
        return(FALSE);
     }
  
     time(&amp;tend);
     tend = tend + gTimeOut;
     clen = clen + iret;
     if (clen &gt;= tlen) break;
     s = s + iret;
     rlen = rlen - iret;
  
  }
  </code></pre>