title: How to detect a disconnected socket C#?
body: <p>I've been working on a socket client program in C# and am wondering how to detect when the other end of a socket has disconnected itself "ungracefully" as in a network cable being unplugged or a hard reset.  </p>
  
  <p>I have these functions below to access the socket and according to the SO question <a href="https://stackoverflow.com/questions/515458/how-can-i-check-whether-a-tcp-socket-is-disconnected-in-c">here</a> and this <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx" rel="nofollow noreferrer">MSDN article</a>, the best way to check for a disconnected socket is to send a 1-byte message with a length of 0.  If an exception is thrown and WSAEWOULDBLOCK is not the error code then the socket is disconnected.  I have tried this but after hard reseting the server connection the client will call <code>Send(new byte[1], 0, 0, SocketFlags.None)</code> and return successfully and the <code>Receive()</code> command right afterwards returns the WSAEWOULDBLOCK error.  </p>
  
  <p>What gives??</p>
  
  <p>Here's my code below.  <code>_socket</code> is set to non-blocking mode:</p>
  
  <pre><code>private int nonBlockRecv(byte[] recvBytes, int offset, int size, SocketFlags sf)
  {
      int bytesRecv = 0;
  
      while (true)
      {
          try
          {
              nonBlockSend(new byte[1], 0, 0, sf);
              bytesRecv = _socket.Receive(recvBytes, offset, size, sf);
              break;
          }
          catch (SocketException excp)
          {
              if (excp.ErrorCode != 10035) // WSAEWOULDBLOCK
                  throw excp;
          }
      }
  
      return bytesRecv;
  }
  
  private int nonBlockSend(byte[] sendBytes, int offset, int size, SocketFlags sf)
  {
      int bytesSent = 0;
  
      while (true)
      {
          try
          {
              _socket.Send(sendBytes, offset, size, sf);
              break;
          }
          catch (SocketException excp)
          {
              if (excp.ErrorCode != 10035) // WSAEWOULDBLOCK
                  throw excp;
          }
      }
  
      return bytesSent;
  }
  </code></pre>
  
  <p>Edit: This may be beneficial but the server is Windows Mobile device. I read in another thread that different OSs maybe able to send socket close signals when they're dying.  Perhaps the Windows Mobile OS does not do this??</p>