【发布时间】:2016-06-09 10:23:18
【问题描述】:
这是我喜欢使用的方法。我相信,这段代码没有什么新东西。
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; -
热连;感谢您的输入。你实际上是对的。
-
Jeoren 的评论可能会拯救我的一天。它返回一个字节数组,其中包含我期望的数据。但是,这个想法是使用这种方法来处理更大的数据,大小随机。然后您可以分块使用数据,以避免内存不足或任何其他 IO 问题。如果是这种情况,我仍然想在未来的扩展中使用这种方法,那么“Stream.Read”有什么问题呢?谢谢。