Patrick Huizinga
Patrick Huizinga

Reputation: 1340

will streaming Socket.Receive block until it fills the buffer?

I want to receive a stream of data. So at times the data can dry up. In that case it would be nice if the Receive method returned what it has received so far.

When I'm using a .Net Socket and I call it's Receive method, will that call block until it is able to completely fill the buffer? Or will it return as soon as it's able to return at least 1 byte? (assuming the socket isn't closed)

Would it matter if I passed a size parameter explicitly? And would the async method BeginReceive have any influence? (I guess in both those cases the behavior will be the same)

When reading this answer, it seems you should always expect the buffer to be filled, because it advises you to do a while (bytesRead == bytesRequested). But an example in the MSDN documentation uses a while (bytesRead > 0)

Upvotes: 0

Views: 135

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84149

The network stack will give you the minimum of what's available (buffered inside the kernel) and the size of the application buffer you provide. The trick here is that regular receive will block if no data is available yet, and that's the difference between those two while statements you provide - the first one breaks out on a short read, which probably indicates that your next read will block, while the second one looks for end-of-stream, i.e. the socket being closed from the other side.

Upvotes: 1

Related Questions