title: reading stream from network using networkstream and streamreader
body: <ul>
  <li>I'm trying to connect to IRC server using a C# code using async
  methods of NetworkStream and StreamReader.
  <ul>
  <li>It seems like the connection phase is completed successfully, but
  when I'm trying to read data it gets stuck.</li>
  <li>I'm reading line by line until reader.EndOfStream is reached (also
  tried reader.Peek() != -1), but still the loop is not ending...</li>
  </ul></li>
  </ul>
  
  <p>Here's the code I'm using:</p>
  
  <pre><code>public class MainViewModel : ViewModelBase
  {
      public string HostAddress { get; set; }
      public int Port { get; set; }
  
      public MainViewModel()
      {
          HostAddress = "amsterdam.nl.eu.undernet.org";
          Port = 6667;
  
          Connect(HostAddress);
      }
  
      private void Connect(string hostAddress)
      {
          var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
          socket.BeginConnect(hostAddress, Port, ConnectCompleted, socket);
      }
  
      private async void ConnectCompleted(IAsyncResult ar)
      {
          var socket = (Socket)ar.AsyncState;
          socket.EndConnect(ar);
  
          var networkStream = new NetworkStream(socket);
          var reader = new StreamReader(networkStream, Encoding.UTF8);
  
  
          do
          {
              var line = await reader.ReadLineAsync();
  
              Console.WriteLine(line);
  
          } while (!reader.EndOfStream);
  
          // Not getting here
  
          await WriteAsync("NICK mickey", networkStream);
          await WriteAsync("USER mickey 8 * : realname", networkStream);
  
          do
          {
              var line = await reader.ReadLineAsync();
  
              Console.WriteLine(line);
  
          } while (!reader.EndOfStream);
  
  
          reader.Close();
          networkStream.Close();
          socket.Close();
      }
  
  
  
      private async Task WriteAsync(string message, NetworkStream stream)
      {
          var command = Encoding.UTF8.GetBytes(string.Format("{0}\r\n", message));
  
          Console.WriteLine("[S] {0}", message);
  
          await stream.WriteAsync(command, 0, command.Length);
  
          await stream.FlushAsync();
  
          Thread.Sleep(1000);
      }
  }
  </code></pre>
  
  <p>The problem is in the Do...While loop in ConnectCompleted()</p>
  
  <p>The output so far is:
  NOTICE AUTH :<strong>* Looking up your hostname
  NOTICE AUTH :<em></strong> Checking Ident
  NOTICE AUTH :<strong></em> Found your hostname
  NOTICE AUTH :*</strong> No ident response</p>
  
  <ul>
  <li>but then stuck... Please help me to understand when stream is over.</li>
  </ul>