我在想是否有必要将
NetworkStream
包裹在BufferedStream
中连续读取,例如1字节、2字节、4字节等...我担心连续调用ReadXxxAsync
会导致多次读取不必要的系统调用或网络 IO。
使用案例:
var stream = tcpClient.GetStream();
var buffer = new byte[4096];
await stream.ReadExactlyAsync(buffer.AsMemory(0, 1));
if (buffer[0] != ...) {
await tcpClient.DisconnectAsync();
return;
}
// Will this cause the 2nd time network IO operation?
// Or only read from kernel network buffer?
await stream.ReadExactlyAsync(buffer.AsMemory(1, 2));
if (BinaryPrimitives.ReadUInt16BigEndian(buffer.AsSpan(1, 2)) != ...) {
await tcpClient.DisconnectAsync();
return;
}
// Will this cause the 3rd time network IO operation?
await stream.ReadExactlyAsync(buffer.AsMemory(3, 2));
var messageBodyLength = BinaryPrimitives.ReadUInt16BigEndian(buffer.AsSpan(3, 2));
var messageBody = buffer.AsMemory(5, messageBodyLength);
await stream.ReadExactlyAsync(messageBody);
...
...
是的,它是缓冲的 - 如果您查看它的方法,您会发现所有
Read
和 Write
方法都接受缓冲区。请参阅https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream?view=net-8.0。