NetworkStream.Read - can it collect partial messages?

狂风中的少年 提交于 2020-01-05 08:16:49

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5687266/networkstream-read-can-it-collect-partial-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!