title: Weird behaviour of SslStream.Read()
body: <p>Working on some socket layers using SslStream. <strong><a href="http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx" rel="nofollow">reference</a></strong></p>
  
  <p>Using the reference, I implemented a simple client. The awkward part is when you run the application, it seems the server is not replying to the client.</p>
  
  <p>Going into the debug screen and setting some breakpoints, I realized it was this function that was on an endless loop.</p>
  
  <pre><code>static string ReadMessage(SslStream sslStream)
  {
      // Read the  message sent by the server. 
      // The end of the message is signaled using the 
      // "&lt;EOF&gt;" marker.
      byte [] buffer = new byte[2048];
      StringBuilder messageData = new StringBuilder();
      int bytes = -1;
      do
      {
          bytes = sslStream.Read(buffer, 0, buffer.Length);
  
          // Use Decoder class to convert from bytes to UTF8 
          // in case a character spans two buffers.
          Decoder decoder = Encoding.UTF8.GetDecoder();
          char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
          decoder.GetChars(buffer, 0, bytes, chars,0);
          messageData.Append (chars);
          // Check for EOF. 
          if (messageData.ToString().IndexOf("&lt;EOF&gt;") != -1)
          {
              break;
          }
      } while (bytes != 0); 
  
      return messageData.ToString();
  }
  </code></pre>
  
  <p>Further investigation pointed out the real criminal here:</p>
  
  <pre><code>bytes = sslStream.Read(buffer, 0, buffer.Length);
  </code></pre>
  
  <p>Seems like, <code>SslStream.Read()</code> is not returning. Checking the <code>byte[] buffer</code> in debug screen reveals that the response has been written to the <code>buffer</code> till <code>crlf</code>. The function has done it's job, still it's not returning with success?!</p>
  
  <p>What could be the reason for this? What steps should I take to ignore with this issue?</p>
  
  <p>Also, for the <strong>skeptical ones</strong>: I used <code>openssl</code> to see if the server is behaving as it should, and everything is fine on the server side.</p>
  
  <p><strong>Note:</strong> I'm already aware of the <code>SslStream.ReadTimeout</code> property. Though it does the job by raising an <code>exception</code> it is not the right answer for every scenario, specially when server is responding with a large stream of data which can only be read efficiently using a while loop and a buffer.</p>