简体   繁体   中英

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM