NetworkStream.Read - 它可以收集部分消息吗?

发布于 2024-11-01 18:26:36 字数 350 浏览 1 评论 0原文

我正在创建一个客户端服务器应用程序,我只是想知道一件事。

客户端将Query对象序列化为String,然后使用NetworkStream将其发送到服务器。

服务器使用 GetStream().Read 读取字节,将其写入缓冲区,将该字符串反序列化为 Query 对象,并获取存储在接收到的查询中的信息。

Read() 方法是否有可能返回部分消息(尚未完全到达)? 或者,例如,在立即发送两条消息的情况下,是否可以通过一次调用 Read() 方法将两条消息读取为一串字节?

或者,也许 NetworkStream 以某种方式知道如何识别完整的消息,并且每个 Read() 都与每个消息相关联?

先感谢您。

I'm creating a client-server application and I'm just wondering about one thing.

Client serializes Query object to String and then uses NetworkStream to send it to the server.

Server reads bytes using GetStream().Read, writes it into a buffer, deserializes that string into a Query object and gets information stored in received query.

Is it possible that Read() method could return partial message (that has not already arrived completely)?
Or, for example, in case of immediate sending two messages, is it possible to read two messages as one string of bytes, by one call of Read() method?

Or maybe NetworkStream somehow knows how to recognize complete messages and each Read() is associated with each message?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮年慕年 2024-11-08 18:26:36

Read()方法是否有可能返回部分消息?

是的,

如果您看到 MSDN 文档它说:

此方法将数据读取到缓冲区参数中,并返回成功读取的字节数。如果没有可供读取的数据,Read 方法将返回 0。Read 操作会读取可用的数据,最多可达 size 参数指定的字节数。如果远程主机关闭连接,并且已接收到所有可用数据,则 Read 方法立即完成并返回零字节。

因此,请务必检查 Read() 方法的返回 (int) 值,并查看该方法是否已读取预期字节数。


如果立即发送两条消息,是否可以通过一次调用 Read() 方法将两条消息读取为一串字节?

很可能没有。

Is it possible that Read() method could return partial message ?

Yes,

if you see MSDN Doc it says:

This method reads data into the buffer parameter and returns the number of bytes successfully read. If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method completes immediately and return zero bytes.

So Always check the returned (int) value of the Read() method and see if the method has read Expected number of Bytes.


In case of immediate sending two messages, is it possible to read two messages as one string of bytes, by one call of Read() method ?

Most Probably No.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文