.NET NetworkStream关闭,如何确保所有数据都已读取?

发布于 2024-09-06 06:58:39 字数 303 浏览 5 评论 0原文

我有一个开放的 TCP 连接,并使用 NetworkStream.BeginRead() 进行读取。一旦连接在任一端关闭,回调就会被调用,流对象就没用了——就像文档所说的那样,EndRead() 会抛出 IOException 或 ObjectDisposeException,具体取决于在这种情况下哪一端终止了连接。

是否可以保证在上次成功的 EndRead(和重新 BegingRead)和断开连接之间不会丢失任何数据,特别是如果我在最后执行此操作?如果不是,万一我最终关闭连接,在断开连接时是否必须手动 NetworkStream.Read() 以确保没有任何未读内容?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昵称有卵用 2024-09-13 06:58:39

在这种情况下使用的模式是使用 BeginRead 读取流(与您正在做的完全一样)并在回调方法中处理“流中的更多数据”情况。
回调方法调用 EndRead 并收集从流中读取的数据(通常通过将其附加到 StringBuilder 实例)然后再次调用 BeginRead。一旦 EndRead 返回 0 字节,就可以保证不再有数据可以从流中读取。

以下是您可能会觉得有用的文档: 使用异步客户端 我注意到

那里没有明确指出 0 字节返回是保证,所以我理解你在这里的困惑,但这个例子非常清楚,这是你退出阅读的信号。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文