title: Async socket - Duplex communication with permanent sockets in c#
body: <p>I'm trying to do asynchronous socket communication, and want the server to keep a list of all connected sockets, so he can broadcast messages to them.</p>
  
  <p>First I took the examples from msdn <a href="http://msdn.microsoft.com/en-us/library/fx6588te%28v=vs.110%29.aspx" rel="nofollow">Asynchronous Socket Server</a> and altered them a little so they don't close the sockets. (just removed the .shutdown and .Close commands)</p>
  
  <p>But doing so, seems to cause the client to hang in the "receiving part".</p>
  
  <p>Here are the changes I made to the msdn examples:</p>
  
  <p>Client:</p>
  
  <p>only changed ReceiveCallback() so it stays in an endless receiving loop:</p>
  
  <pre><code>private static void ReceiveCallback(IAsyncResult ar)
  {
      try
      {
          // Retrieve the state object and the client socket 
          // from the asynchronous state object.
          StateObject state = (StateObject)ar.AsyncState;
          Socket client = state.workSocket;
  
          // Read data from the remote device.
          int bytesRead = client.EndReceive(ar);
  
          if (bytesRead &gt; 0)
          {
              // There might be more data, so store the data received so far.
              state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
  
              // Get the rest of the data.
              client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                  new AsyncCallback(ReceiveCallback), state);
          }
          else
          {
              // All the data has arrived; put it in response.
              if (state.sb.Length &gt; 1)
              {
                  response = state.sb.ToString();
                  Console.WriteLine(state.sb.ToString());
              }
              // Signal that all bytes have been received.
              receiveDone.Set();
  
              // Get the rest of the data.
              client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                  new AsyncCallback(ReceiveCallback), state);
          }
      }
      catch (Exception e)
      {
          Console.WriteLine(e.ToString());
      }
  }
  </code></pre>
  
  <p>The Server:
  just commented out the lines that close the socket:</p>
  
  <pre><code>//handler.Shutdown(SocketShutdown.Both);
  //handler.Close();
  </code></pre>
  
  <p>Later i planed to keep a List of Sockets so i can send Messages to them, but it already fails here.</p>
  
  <p>I'm greatfull for any hints, also I would like to hear your opinion on using this tenique for a server that has to serve at max 100 clients, which could send a request any 2 seconds. (The communication should be both ways, so that the client and the Server can send a Message at any time without waiting for a Message to respond to).</p>
  
  <p>Thank you and good evening
  Martin</p>