【问题标题】:Does TcpClient NetworkStream.Write have concept of end of stream?TcpClient NetworkStream.Write 是否有流结束的概念?
【发布时间】:2014-07-11 09:41:56
【问题描述】:

在一个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?

我注意到DataAvailableGetStream().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);
}

【问题讨论】:

    标签: tcpclient networkstream


    【解决方案1】:

    答案似乎是肯定的,我们必须始终负责读取已发送的相同数量的字节。换句话说,必须有一个应用层协议来准确读取写入底层流的内容,因为它不知道新消息何时开始或结束。

    【讨论】:

    • 没错——这就是为什么他们称它为 stream,而不是 message
    猜你喜欢
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多