我有一台服务器通过 NetworkStream.Read
管理两个客户端。
应用协议(protocol)是:
ClientMessage [128 Bytes] → 来自服务器的响应 [128 Bytes]
现在在服务器端:MyTcpClient.GetStream().Read()
是否可能只返回 < 128 字节,尽管来自客户端的所有消息都正好是 128 字节长?
我猜这样的客户端消息足够短,可以放入 tcp/ip 层上的一个数据包中 - 但是会不会有某种碎片或随机性呢?
NetworkStream.DataAvailable
是防御此问题的正确属性吗?
在顺利运行数小时后,我有时会遇到奇怪的错误和连接丢失,这指向类似的事情。
提前致谢。
最佳答案
Is it possible, that MyTcpClient.GetStream().Read() returns only < 128 Bytes
是的。您不能假设对 Read() 的调用将返回 128 个字节。
参见 docs :
The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
参见 this有关如何正确读取流的链接
尝试这样的事情:(传入一个 128 字节的数组)
private static void ReadWholeArray (Stream stream, byte[] data)
{
int offset=0;
int remaining = data.Length;
while (remaining > 0)
{
int read = stream.Read(data, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}
关于.net - 从网络流中读取 : packet fragmentation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5446409/