Skip to content

Stream.Read

Peter Foot edited this page Mar 31, 2017 · 1 revision

Stream.Read and the Number of Bytes Returned

{{ Public Function Read(ByVal buffer As Byte(), ByVal offset As Integer, ByVal count As Integer) As Integer }}In all situations there is no guarantee that any call to Stream.Read will return the full number of bytes requested in the count argument. This is particularly the case on NetworkStream and SerialPort Stream etc. The Read method is allowed to return as soon as one byte is available. One must thus always use the return value, looping until the required number of bytes has been received, see the example below.

Read also returns when the ‘end’ of the stream has been reached, returning zero in that case. For NetworkStream ‘end of stream’ occurs when the connection has been closed — when the connection was closed “gracefully”; closure due to error is signalled by an exception.

For more information see e.g. http://www.yoda.arachsys.com/csharp/readbinary.html

Stream.Read returning fewer bytes is more likely when there’s a network or other communications involved. For instance all of today’s common transport protocols TCP/IP’s TCP, Bluetooth RFCOMM, and IrDA TinyTP are allowed to split and recombine the data as they see fit. They are allowed to split for instance to carry the data within the maximum packet size, and they are allowed to coalesce data for instance for efficiency to fill a packet with data from multiple send calls.

Clone this wiki locally