title: High performance asynchronous awaiting sockets
body: <p>I am writing an app that will require to make hundreds of socket connections over tcp to read/write data.</p>
  
  <p>I have come across <a href="http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx" rel="noreferrer">this code snippet here</a> and I'm wondering how I can make this more robust.</p>
  
  <p>This is currently how I am calling the code:</p>
  
  <pre><code>foreach (var ip in listofIps)
  {
     IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), 4001);
     Socket client = new Socket(AddressFamily.InterNetwork,
                             SocketType.Stream, ProtocolType.Tcp);
     client.Connect(remoteEP);
     await ReadAsync(client);
  }
  </code></pre>
  
  <ol>
  <li><p>Is there anything wrong with the above, and how can it be optimized such that it runs concurrently?</p>
  
  <p>In the code snippet, the buffer size is set to 1000. Just as a simple illustration, if I were to attempt to print out only the bytes received, and not the remaining 0x00s, I have to do something like this:</p>
  
  <pre><code>while (true)
  {
      await s.ReceiveAsync(awaitable);
      int bytesRead = args.BytesTransferred;
      if (bytesRead &lt;= 0) break;
      var hex = new StringBuilder(bytesRead * 2);
      var msg = new byte[bytesRead];
  
      for (int i = 0; i &lt; bytesRead; i++)                
          msg[i] = args.Buffer[i];                
  
      foreach (byte b in msg)                
          hex.AppendFormat("{0:x2} ", b);
  
      AppendLog(string.Format("RX: {0}", hex));
  }
  </code></pre></li>
  <li><p>Is there a more efficient way of doing this? Previously, I would iterate the whole buffer and print out the data, but that will give me a whole bunch of trailing 0x00s as my protocol is anywhere between 60 to 70 bytes long.</p></li>
  </ol>