开发者

NetworkStream.Read - can it collect partial messages?

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开发者_StackOverflow社区 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜