title: Sockets in C#, how can I asynchronously read and write data through a NetworkStream
body: <p>[I am limited to Visual Studio 2010, and therefore, C# 4. async and await are not available to me.]</p>
  
  <p>I'm working on network architecture for a project of mine, that sends packets of data over a network between a server and a client, but the client and server must continue running while waiting, so the code has to be non-blocking, so I thought to use the asynchronous methods. However, except for simple synchronous one-time IO, I don't know much about what to do, especially when using a NetworkStream. What I'm trying to do is:</p>
  
  <p>1) Client connects to server</p>
  
  <p>2) Server accepts connection</p>
  
  <p>3) Server waits for data from client</p>
  
  <p>4) Server processes data</p>
  
  <p>5) Server responds to client</p>
  
  <p>6) While connection is open, repeat from 3.</p>
  
  <p>And I would like to use a NetworkStream to wrap the socket. But I am new to asynchronous I/O and i'm not really sure how to do this without blocking other parts of the server/client code when waiting for a response, especially with a NetworkStream. In my research I see examples that use something like this:</p>
  
  <pre><code>while(true){
      socket.BeginAccept(new AsyncCallback(AcceptCallback), socket );
  }
  </code></pre>
  
  <p>But it seems like that loop would still hold up the application. Can anyone give me some pointers (ha) on how exactly to do this? I haven't been able to find many examples that keep the connection open, only Client Connect -> Client Send -> Server Recieve -> Server Send -> Disconnect. I'm not asking for full code, just the general idea with a few snippets.</p>