title: Handling timeout on blocking .NET socket
body: <p>A TcpClient instance, created with the Accept method, is used for manage a client connection. The problem arise when I need to terminate the server thread, since it is blocked on a receive call.</p>
  
  <p>So I setup a the TcpClient ReceiveTimeout in order to loop every <em>n</em> milliseconds to test the exit condition. The result is that the Receive operation raise an exception (SocketException) having the error code SocketError.TimedOut. Good I was thinking...</p>
  
  <p>The problem is that the property <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx" rel="nofollow noreferrer">Socket.Connected</a> returns false, but as stated in the MSDN documentation:</p>
  
  <blockquote>
    <p>The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.</p>
  </blockquote>
  
  <p>So, I do what states:</p>
  
  <pre><code>try {
       // Receive operation on socket stream
       // Send operation on socket stream
  } catch (SocketException e) {
      if (e.SocketErrorCode == SocketError.TimedOut) {
      try {
          IAsyncResult asyncResult;
          int sResult;
  
          asyncResult = mSocket.Client.BeginSend(new byte[] {}, 0, 0, SocketFlags.None, delegate(IAsyncResult result) { }, null);
          sResult = mSocket.Client.EndSend(asyncResult);
          Debug.Assert(asyncResult.IsCompleted == true);
  
          if (mSocket.Connected == false)
              throw new Exception("not more connected");  // Always thrown
      } catch (Exception e) {
               // ...
          }
  }
  </code></pre>
  
  <p>But, even if the aynch Send operation is executed, the property <em>mSocket.Connected</em> is always false, causing the outer loop to terminate (other threads calls Disconnect method to terminate the server thread).</p>
  
  <p>What am I missing?</p>