在TcpClient / TcpListener设置中,与接收端的观点有什么不同:
// Will sending a prefixed length before the data...
client.GetStream().Write(data, 0, 4); // Int32 payload size = 80000
client.GetStream().Write(data, 0, 80000); // payload
// Appear as 80004 bytes in the stream?
// i.e. there is no end of stream to demarcate the first Write() from the second?
client.GetStream().Write(data, 0, 80004);
// Which means I can potentially read more than 4 bytes on the first read
var read = client.GetStream().Read(buffer, 0, 4082); // read could be any value from 0 to 4082?
我注意到DataAvailable
和GetStream().Read()
的返回值无法可靠地判断是否有传入数据。我是否总是需要编写一个Read()循环来准确读取前4个字节?
// Read() loop
var ms = new MemoryStream()
while(ms.length < 4)
{
read = client.GetStream().Read(buffer, 0, 4 - ms.length);
if(read > 0)
ms.Write(buffer, 0, read);
}
答案 0 :(得分:1)
答案似乎是肯定的,我们必须始终负责读取发送的相同字节数。换句话说,必须有一个应用程序级协议来准确读取写入底层流的内容,因为它不知道新消息何时开始或结束。