2011-12-29 65 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