title: Best practice to detect a client disconnection in .NET?
body: <p>I'm developing a server in C# which can accept only one client and I need to know when this client is disconnected to be able to accept another connection requests.</p>
  
  <p>I'm using a first Socket which continuously listen to connection request with <code>Socket.BeginAccept</code> and accept or reject clients. When a client is accepted, the new Socket which is returned by <code>Socket.EndAccept</code> is used for the communication between client and server. Then, the server waits for commands from the client with <code>Socket.Begin/EndReceive</code> and sends responses. The server uses a Telnet-like protocol, which means that each command and each line of response must end with <code>\r\n</code>.</p>
  
  <p>To detect if the client has been disconnected, I've installed a timer which sends every 500ms an empty message ("<code>\r\n</code>") to the client. If the client is disconnected, an exception is thrown by the Socket. This exception is caught by the server which closes the current session and accepts new connection. This solution is robust but implies unneeded traffic over the network and must be handled correctly by the client which must filter dummy messages before getting an actual response. </p>
  
  <p>I've tried to send an empty buffer (<code>Socket.Send(new byte[1], 0, 0)</code>), but it seems that doesn't work in the direction server->client.</p>
  
  <p>Another solution might be to handle the case where <code>Socket.EndReceive</code> returns 0 byte. It works fine for the case of a disconnection which occurs during "idle" time. But if the client disconnects during a message transfert, the server doesn't always see it and waits indefinitely.</p>
  
  <p>I've already seen several threads and questions about this problem, but I've never seen any good solution.</p>
  
  <p>So my question is: what is the best way to detect a disconnection in .Net ?</p>