Assume I have simple protocol implemented over TCP, where each message is made up of:
int indicating data length.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.
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).
Something, somewhere is going to have to loop. After all, multiple socket reads could be required.
I believe that BinaryReader.Read will keep looping until either it's read as much as you've asked for or hit the end of the stream, but assuming you would want to throw an exception if you reached the end of the stream, I'd write personally write a separate method. It's easy enough to implement in one place and reuse, after all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With