title: How can I check whether a (TCP) socket is (dis)connected in C#?
body: <p>How should I check a (TCP) socket to find out whether it is connected?</p>
  
  <p>I have read about the <code>Socket.Connected</code> property in <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx" rel="noreferrer">MSDN</a>, but it says it only shows the state according to the last I/O. This isn't useful for me, since I want to do this <em>before</em> trying to read from the socket. The remarks section also notes that:</p>
  
  <blockquote>
    <p>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>The example on the same page shows how to do it.<sup>(1)</sup> But <a href="http://bytes.com/groups/net-c/258127-how-use-socket-connected-property-properly#post1039238" rel="noreferrer">a post by Ian Griffiths</a> says that I should <em>read</em> from the socket, not <em>send</em> through it.</p>
  
  <p><a href="http://www.eggheadcafe.com/software/aspnet/33035784/cs-socketconnect-retur.aspx#ctl00_MiddleContent_NewsGroupPosts" rel="noreferrer">Another post by Pete Duniho</a> says:</p>
  
  <blockquote>
    <p>... after you've called <code>Shutdown()</code>,
    call <code>Receive()</code> until it returns <code>0</code>
    (assuming the remote endpoint isn't
    actually going to send you anything,
    that will happen as soon as the remote
    endpoint has received all of your
    data).  Unless you do that, you have
    no assurance that the remote endpoint
    has actually received all of the data
    you sent, even using a lingering
    socket.</p>
  </blockquote>
  
  <p>I don't really understand his statement about calling <code>Receive()</code> to make sure that the remote endpoint has actually received all the data I <em>sent</em>. (Do sockets block receiving until the sending buffer is empty?)</p>
  
  <p>I am confused by the different methods proposed. Could you please explain them?</p>
  
  <hr>
  
  <p>(1) I wonder why the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx" rel="noreferrer">example</a> for the <code>Socket.Connected</code> property allocates a 1-byte array, even though it calls <code>Send</code> with 0 length?</p>