title: How do i handle clients better with TCPListener?
body: <p>I had a problem with <a href="https://stackoverflow.com/questions/3315186/problems-with-too-many-connections">too many connections</a> After a few test i deducted the problem is with MY server. The fact that the server listening port was on the left side should have told me.</p>
  
  <p>When running the same client code using a server on a different machine i dont get hundreds of ports opened. When my server on my local machine i get > 200 connects connecting to my listening port. I think i am handling clients wrong. My code is below with all non server and client code removed</p>
  
  <pre><code>{
      TcpListener server = null;
      server = new TcpListener(port);
      server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
      server.Start();
  
      while (true)
      {
          var client = server.AcceptTcpClient();
          using(var stream = client.GetStream()) {
          ...
          stream.Read(...
          ...
          stream.Write(...
          } //using above should close this.
          client.Close();
      }
      server.Stop();
  }
  </code></pre>
  
  <hr>
  
  <p>I modified the code to use asynchronous connections and it locks up the 2nd time it does stream.Read just under the while (client.Connected)</p>
  
  <pre><code>    server = new TcpListener(port);
      server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
      server.Start();
      server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), server);
      while (true)
          Thread.Sleep(1000); //infinite loop for testing
  
  
  
  
  public void DoAcceptTcpClientCallback(IAsyncResult ar)
  {
      Byte[] bytes = new Byte[1024 * 4];
      TcpListener listener = (TcpListener)ar.AsyncState;
      using (TcpClient client = listener.EndAcceptTcpClient(ar))
      {
          using (var stream = client.GetStream())
          using (var ostream = new MemoryStream())
          {
              while (client.Connected)
              {
                  int i;
                  while ((i = stream.Read(bytes, 0, bytes.Length)) == bytes.Length)
                      ostream.Write(bytes, 0, i);
  
                  ostream.Write(bytes, 0, i);
                  szresults = Func(ostream)
                  var obuf = Encoding.UTF8.GetBytes(szresults);
                  stream.Write(obuf, 0, obuf.Length);
              }
          }
          client.Close();
      }
  }
  </code></pre>