NetworkStream 读取的字节数少于预期

NetworkStream reads fewer bytes than expected

如果 messageBytes.Length 足够大(例如 30,000 左右),则 stream.Read 读取的字节数少于预期。

Using stream As New Net.Sockets.NetworkStream(socket)
    networkStream.Read(messageBytes, 0, messageBytes.Length)
End Using

MSDN 的 documentation 在其 备注 部分

中声明了这一点

An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.

我能够在 while 循环中读取它,读取单个字节,直到到达所需的位置,比如

Dim position = 0
While position < messageBytes.Length
    stream.Read(messageBytes, position, 1)
    position += 1
End While

问题是谁能说出为什么实施允许这样做?我以为 Stream.Read 方法是阻塞的,所以它应该等到流中的所有字节都可用并成功读取。

它会阻塞,直到可以读取 一些 数据。如果您在数据到达时对其进行处理,这一点非常重要。例如,如果您要将数据写入文件,您最好立即开始写入,而不是等到所有数据都下载完毕。

它还可以处理比内存中更多的数据。

虽然您不需要逐字节读取它,即:

public byte[] ReadFixedLength(this Stream stream, int length)
{
    byte[] buffer = new byte[length];
    int offset = 0;
    while (length > 0)
    {
        int read = stream.Read(buffer, offset, length);
        if (read == 0)
        {
            throw new EndOfStreamException();
        }

        offset += read;
        length -= read;
    }

    return buffer;
}