.NET NetworkStream closed, how to be sure all data is read?

扶醉桌前 提交于 2019-12-11 06:28:30

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3067969/net-networkstream-closed-how-to-be-sure-all-data-is-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!