2016-06-09 81 views
1

以下是我喜歡使用的方法。我相信,這個代碼沒有新東西。Stream.Read不返回收到的數據

public static byte[] ReadFully(Stream stream, int initialLength) 
    { 
     // If we've been passed an unhelpful initial length, just 
     // use 1K. 
     if (initialLength < 1) 
     { 
      initialLength = 1024; 
     } 

     byte[] buffer = new byte[initialLength]; 
     int read = 0; 

     int chunk; 
     while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) 
     { 
      read += chunk; 

      // If we've reached the end of our buffer, check to see if there's 
      // any more information 
      if (read == buffer.Length) 
      { 
       int nextByte = stream.ReadByte(); 

       // End of stream? If so, we're done 
       if (nextByte == -1) 
       { 
        return buffer; 
       } 

       // Nope. Resize the buffer, put in the byte we've just 
       // read, and continue 
       byte[] newBuffer = new byte[buffer.Length * 2]; 
       Array.Copy(buffer, newBuffer, buffer.Length); 
       newBuffer[read] = (byte)nextByte; 
       buffer = newBuffer; 
       read++; 
      } 
     } 
     // Buffer is now too big. Shrink it. 
     byte[] ret = new byte[read]; 
     Array.Copy(buffer, ret, read); 
     return ret; 
    } 

我的目標是讀取TCP客戶端發送的數據,例如box{"id":1,"aid":1} 這是一個命令來解釋我的應用程序中類似Jason的文本。 而且這段文字不一定每次都是相同的大小。 下一次可以有run{"id":1,"aid":1,"opt":1}

該行調用的方法;

var serializedMessageBytes = ReadFully(_receiveMemoryStream, 1024); 

Please click to see; Received data in receiveMemoryStream 雖然我們可以看到流中的數據, 在ReadFully方法,「chunck」總是返回0和方法返回{byte[0]}

任何幫助非常感謝。

+0

爲什麼不使用'stream.CopyTo(memoryStream)'然後'memoryStream.ToArray()'? –

+0

由於緩衝區? –

+0

在引擎蓋下,流的默認緩衝區大小是'DefaultCopyBufferSize = 81920;' –

回答

1

在觀察窗口中查看您的流,流(19)的位置位於數據的末尾,因此沒有剩下可讀的內容。這可能是因爲您剛剛將數據寫入了數據流,並且沒有重新設置位置。

在函數的開頭添加一個stream.Position = 0;stream.Seek(0, System.IO.SeekOrigin.Begin);語句,如果您很樂意始終從流的開頭讀取數據或檢查填充流的代碼。請注意,雖然某些流實現不支持搜索。

+0

傑克遜,趕上。一旦我將這個位置倒回到0,它就開始工作了。事實上,在調用該方法之前有一個重置。 '_receiveMemoryStream.Position = 0;'。但是,在重置和方法調用之間,還有一些使用流的調用,並且很可能他們再次離開陣列末尾的位置。所以,快樂的結局。謝謝。 – Sener