views:

103

answers:

1

I've an open TCP connection, and reading using NetworkStream.BeginRead(). Once the connection is closed at either end, the callback is called and the stream object is useless - like documentation says, EndRead() throws IOException or ObjectDisposedException depending in this case on which end terminated the connection.

Is it guaranteed that there isn't any data I'm missing just in between the last successful EndRead (and the re-BegingRead) and disconnection, particularly if I do it at my end? If it isn't, in case I'm the end closing the connecting, do I have to manually NetworkStream.Read() when disconnecting to make sure nothing is left unread?

A: 

The pattern to use in this case is to use BeginRead to read the stream (exactly like you're doing) and to handle the 'more data in stream' case in the callback method.
The callback method calls EndRead and collects the data read from the stream (typically by appending it to a StringBuilder instance) and then calls BeginRead again. As soon as EndRead returns 0 bytes, that's your guarantee that there's no more data to be read from the stream.

Here's the documentation you might find useful: Using async client sockets

I noticed that nowhere in there did it specifically state that the 0 byte return was the guarantee, so I understand your confusion here, but the example is very clear that that's your signal to quit reading.

Task
Woo-hoo! I know stuff that is correct but that absolutely nobody else knows enough about to confirm or deny! Uh, wait a minute, why am I happy about this?
Task