title: Why the TCP server socket is closed unexpectedly?
body: <p>I have created a Win32 server-client application, where many clients connect to a single server, send queries and <code>recv</code> responses. </p>
  
  <p>It works fine in many installations, but the connection is closed in some others. Both client and server report that the connection is closed by the remote host. The sequence of socket operations after the connection is created is this:</p>
  
  <pre><code>Client: sends query Q1 (by calling send)
  Server: recvs query Q1 and sends R1
  Client: recvs R1
  Client: sends query Q2
  Server: recvs query Q2 and sends R2
  Client: recvs R2
  and so on
  </code></pre>
  
  <p>In some networks, after a period of time, for example, 1 hour or 10 minutes,</p>
  
  <pre><code>    Client: Sends Q(n) successfully
      Server: recvs SOCKET_ERROR and my code exits thread. 
  //unexpected
     WSAGetLastError() at server returns 10054: An existing connection was forcibly closed by the remote host. 
      Client: recvs SOCKET_ERROR. 
  WSAGetLastError() at client also returns 10054
  </code></pre>
  
  <p>In server there is one thread for each client. The server has negligible delay before responding.</p>
  
  <p>Why does the function <code>recv()</code> at the server side return SOCKET_ERROR? Who closes the socket?
  Edit: I updated the question and put the WSAGetLastErrorCode() return value.
  Why -1? What is wrong with this question?</p>