As noted, usually reading can return fewer bytes, then it was said. See the Workaround below, which ensures that it reads as many bytes as it was said - basically the size of the buffer passed. Function from here .
/// Reads data into a complete array, throwing an EndOfStreamException /// if the stream runs out of data first, or if an IOException /// naturally occurs. /// </summary> /// <param name="stream">The stream to read data from</param> /// <param name="data">The array to read bytes into. The array /// will be completely filled from the stream, so an appropriate /// size must be given.</param> public static void ReadWholeArray (Stream stream, byte[] data) { int offset=0; int remaining = data.Length; while (remaining > 0) { int read = stream.Read(data, offset, remaining); if (read <= 0) throw new EndOfStreamException (String.Format("End of stream reached with {0} bytes left to read", remaining)); remaining -= read; offset += read; } }
First you can use this method to read: 2 byte integer , which should represent the number of bytes that will follow. Then you read again, but now read as many bytes as indicated in this double-byte whole.
But for this to work, it is clear that the sender must first send an integer of two bytes, which is the length of the data that will follow, and then the data itself.
So basically you call the function above in a byte array of size two first (to get the length of the data), and then in the byte array with the size specified in that 2-byte integer (to get the data).
You can use this to read from NetworkStream . A few more readings on this topic.
source share