2011-12-29 61 views
1

我正在使用SslStream来加密客户端和服务器之间的TCP连接。问题是,当客户端读取数据时,它可能会被赋予一堆零字节而不是实际的数据。这里是展示问题的示例:奇怪的SslStream缓冲问题

 // Server 
     using (NetworkStream tcpStream = client.GetStream()) 
     { 
      Stream stream = tcpStream; 
      if (ssl) 
      { 
       SslStream sslStream = new SslStream(tcpStream, true); 
       sslStream.AuthenticateAsServer(cert, false, SslProtocols.Default, false); 
       stream = sslStream; 
      } 

      byte[] buf = new byte[] {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02}; 
      stream.Write(buf, 0, buf.Length); 

      buf = new byte[] {0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03}; 
      stream.Write(buf, 0, buf.Length); 
     } 



     // Client 
     using (NetworkStream tcpStream = client.GetStream()) 
     { 
      Stream stream = tcpStream; 
      if (ssl) 
      { 
       SslStream sslStream = new SslStream(
        tcpStream, 
        true, 
        delegate { return true; } 
       ); 
       sslStream.AuthenticateAsClient(
        "localhost", 
        null, 
        SslProtocols.Default, 
        false 
        ); 
       stream = sslStream; 
      } 

      byte[] buf = new byte[7]; 
      stream.Read(buf, 0, buf.Length); 
      // buf is 01010101010101 as expected 

      buf = new byte[9]; 
      stream.Read(buf, 0, buf.Length); 
      // buf is 020000000000000000 instead of the expected 020303030303030303 
      // a subsequent read of 8 bytes will get me 0303030303030303 
      // if the ssl bool is set to false, then the expected data is received without the need for a third read 
     } 

看来好像客户需求为服务器写了他们正在使用的SslStream只有在完全相同的字节数从流中读取。这不可能是正确的。我在这里错过了什么?

回答

3

此代码

buf = new byte[9]; 
stream.Read(buf, 0, buf.Length); 

请求stream 1首9个字节之间读入buf。它并不总是完全读取9个字节。

Read Method返回实际读取的字节数。

试试这个:

byte[] buffer = new byte[9]; 
int offset = 0; 
int count = buffer.Length; 

do 
{ 
    int bytesRead = stream.Read(buffer, offset, count); 
    if (bytesRead == 0) 
     break; // end of stream 
    offset += bytesRead; 
    count -= bytesRead; 
} 
while (count > 0); 
+0

啊,很业余的错误。我想我只是非常无知,因为TcpStream总是给我我想要的东西。那么我想,无论我从哪个代码读取流,我都应该使用这里描述的逻辑?当流读取完成时,似乎是效用函数的一个很好的候选者。 – Dennis 2011-12-29 16:47:32