title: Odd performance with C# Asynchronous server socket
body: <p>I'm working on a web server in C# and I have it running on Asynchronous socket calls. The weird thing is that for some reason, when you start loading pages, the 3rd request is where the browser won't connect. It just keeps saying "Connecting..." and doesn't ever stop. If I hit stop. and then refresh, it will load again, but if I try another time after that it does the thing where it doesn't load again. And it continues in that cycle. I'm not really sure what is making it do that. </p>
  
  <p>The code is kind of hacked together from a couple of examples and some old code I had. Any miscellaneous tips would be helpful as well.</p>
  
  <p>Heres my little Listener class that handles everything</p>
  
  <p>(<a href="http://pastie.org/951240" rel="nofollow noreferrer">pastied here</a>. thought it might be easier to read this way)</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Net;
  using System.Net.Sockets;
  using System.Text;
  using System.Threading;
  using irek.Request;
  using irek.Configuration;
  namespace irek.Server
  {
      public class Listener
      {
          private int port;
          private Socket server;
          private Byte[] data = new Byte[2048];
          static ManualResetEvent allDone = new ManualResetEvent(false);
          public Config config;
  
          public Listener(Config cfg)
          {
              port = int.Parse(cfg.Get("port"));
              config = cfg;
              ServicePointManager.DefaultConnectionLimit = 20;
          }
  
          public void Run()
          {
              server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
              IPEndPoint iep = new IPEndPoint(IPAddress.Any, port);
              server.Bind(iep);
  
              Console.WriteLine("Server Initialized.");
              server.Listen(5);
              Console.WriteLine("Listening...");
              while (true)
              {
                  allDone.Reset();
                  server.BeginAccept(new AsyncCallback(AcceptCon), server);
                  allDone.WaitOne();
              }
  
          }
  
          private void AcceptCon(IAsyncResult iar)
          {
              allDone.Set();
              Socket s = (Socket)iar.AsyncState;
              Socket s2 = s.EndAccept(iar);
              SocketStateObject state = new SocketStateObject();
              state.workSocket = s2;
              s2.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state);
          }
  
          private void Read(IAsyncResult iar)
          {
              try
              {
                  SocketStateObject state = (SocketStateObject)iar.AsyncState;
                  Socket s = state.workSocket;
  
                  int read = s.EndReceive(iar);
  
                  if (read &gt; 0)
                  {
                      state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
  
                      SocketStateObject nextState = new SocketStateObject();
                      nextState.workSocket = s;
                      s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), nextState);
                  }
                  if (state.sb.Length &gt; 1)
                  {
                      string requestString = state.sb.ToString();
                      // HANDLE REQUEST HERE
                      byte[] answer = RequestHandler.Handle(requestString, ref config);
                      // Temporary response
                      /*
                      string resp = "&lt;h1&gt;It Works!&lt;/h1&gt;";
                      string head = "HTTP/1.1 200 OK\r\nContent-Type: text/html;\r\nServer: irek\r\nContent-Length:"+resp.Length+"\r\n\r\n";
                      byte[] answer = Encoding.ASCII.GetBytes(head+resp);
                      // end temp.
                      */
                      state.workSocket.BeginSend(answer, 0, answer.Length, SocketFlags.None, new AsyncCallback(Send), s);
                  }
              }
              catch (Exception e)
              {
                  Console.WriteLine(e.Message);
                  Console.WriteLine(e.StackTrace);
                  return;
              }
          }
  
          private void Send(IAsyncResult iar)
          {
              try
              {
                  SocketStateObject state = (SocketStateObject)iar.AsyncState;
                  int sent = state.workSocket.EndSend(iar);
                  state.workSocket.Shutdown(SocketShutdown.Both);
                  state.workSocket.Close();
              }
              catch (Exception)
              {
  
              }
              return;
          }
      }
  }
  </code></pre>
  
  <p>And my SocketStateObject:</p>
  
  <pre><code>public class SocketStateObject
  {
      public Socket workSocket = null;
      public const int BUFFER_SIZE = 1024;
      public byte[] buffer = new byte[BUFFER_SIZE];
      public StringBuilder sb = new StringBuilder();
  }
  </code></pre>
  
  <p>** EDIT **</p>
  
  <p>I have updated the code with some suggestions from Chris Taylor.</p>