title: How should I handle socket disconnections in .NET?
body: <p>I'm building a (LAN) network application, so there is always the possibility that a connection will be disconnected, for various possible reasons. I am trying to think of a good design for handling this issue, such that it doesn't affect the rest of the application. I wrote a quick thing to try to do it, but I think it can be enhanced a lot. I appreciate your help and experience about the best way to handle this issue.</p>
  
  <p>This is my first trial:</p>
  
  <pre><code>class ConnectionWrapper {
      NetworkStream stream;
      StreamReader reader;
      Endpoint endPoint;
      bool endOfStream;
      int maxRetries = 5;
  
      public void connect() {
          // ... code to initialize a (TCP) socket to endPoint
          this.stream = new NetworkStream(socket, true);
          this.reader = new StreamReader(stream);
      }
  
      string readNextMsg() {
          try {
              string msg = reader.ReadLine();
              if (msg == "EOF") endOfStream = true;
              return msg;
          }
          catch (IOException e) {
              Exception ex = e;
              while (maxRetries-- &gt; 0) {
                  try { connect(); ex = null; }
                  catch (Exception e2) { ex = e2; }
              }
              if (x != null) throw ex;
          }
      }
  }
  </code></pre>
  
  <p>Not very elegant, and probably not the best that can be done. Could you please share your experience, and may be even suggest an existing library?</p>
  
  <p>Thank you.</p>