Jon said:
I setup a socket to receive an 8k byte array on it's own thread in my C#
application.
I found that the Receive method did not read all 8k and I had to loop
and read in chunks in order to receive all 8k.
Why doesn't the Receive method block until all data is read?
The primary answer: because that's how it's defined to work.
The elaboration: it is actually impossible for Receive() to guarantee
that it will fill the buffer you passed to it. If the end-of-stream is
reached before the buffer is filled, your choices are either:
-- block indefinitely, or
-- return before the buffer is filled
Presumably you would not like the method to block indefinitely. So,
your code _always_ has to be able to handle the situation where the
buffer you passed in is not completely filled.
This is true for all types of streams; for network streams, you also
have the issue that for a given stream, not all of the data necessarily
will even be sent all at once, nor is possible to know the length of the
data that has been sent. It's quite common to have a single connection
over which some kind of interactive communication is performed. If
Receive() waited until its buffer was filled before it returned,
arbitrary, inefficient requirements would have to be imposed on
application protocols, just so that the receiver could know the size of
the buffer to be passed.
Instead, applications are allowed to implement whatever application
protocol they want or need to, and the method is simply defined to do
the best it can.
Is there another method that will "ReadFully" or is there a buffer I
need to set?
Not in the Socket class. Depending on what you're doing, you may find
the WebClient.DownloadFile() method useful, or it may well be that you
are mistaken in your belief that your code can be correctly written
while still assuming that the buffer you pass to the Receive() method
will always be filled.
Pete