NetworkStream.Read-它可以收集部分消息吗? [英] NetworkStream.Read - can it collect partial messages?

查看:123
本文介绍了NetworkStream.Read-它可以收集部分消息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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.

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

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?

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

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

谢谢.

推荐答案

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

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

是的

如果您看到 MSDN文档

if you see MSDN Doc it says:

此方法将数据读入buffer参数并返回成功读取的字节数.如果没有数据可读取,则Read方法将返回0.Read操作将读取尽可能多的数据,直到size参数指定的字节数为止.如果远程主机关闭了连接,并且已收到所有可用数据,则Read方法将立即完成并返回零字节.

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.

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


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


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

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 ?

最可能不是.

这篇关于NetworkStream.Read-它可以收集部分消息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆