以下是我喜歡使用的方法。我相信,這個代碼沒有新東西。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]}
。
任何幫助非常感謝。
爲什麼不使用'stream.CopyTo(memoryStream)'然後'memoryStream.ToArray()'? –
由於緩衝區? –
在引擎蓋下,流的默認緩衝區大小是'DefaultCopyBufferSize = 81920;' –