Assume I have simple protocol implemented over TCP, where each message is made up of:
- An
int
indicating data length. - Binary data, of the length specified in 1.
Reading such a message I would like something like:
int length = input.ReadInt();
byte[] data = input.ReadBytes(length);
Using Socket.Receive
or NetworkStream.Read
the available number of bytes is read. I want the call to ReadBytes
to block until length
bytes are available.
Is there a simple way to do this, without having to loop over the read, restarting at an offset waiting for the remaining data?
In a real application the read should probably be done Async or on a background thread, but I've ignored that for now. The important thing is to be able to have the read not complete until all data is available.
Edit
I know that I can buffer the data myself, and I know how to do it. It's just a loop around Receive
that continues at the next offset. What I am asking for is if there is a reusable implementation of such a loop, without the need for an own loop of any kind (or alternatively a reusable Async implemenation that finishes when all data is available).