.NET NetworkStream 关​​闭,如何确保读取所有数据? [英] .NET NetworkStream closed, how to be sure all data is read?

查看:71
本文介绍了.NET NetworkStream 关​​闭,如何确保读取所有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个开放的 TCP 连接,并使用 NetworkStream.BeginRead() 读取.一旦连接在任一端关闭,回调将被调用并且流对象无用 - 就像文档说的那样,EndRead() 抛出 IOException 或 ObjectDisposedException 取决于在这种情况下终止连接的一端.

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.

是否可以保证在最后一次成功的 EndRead(和重新开始读取)和断开连接之间没有我丢失的任何数据,特别是如果我最后这样做了?如果不是,万一我最终关闭连接,我是否必须在断开连接时手动使用 NetworkStream.Read() 以确保没有任何未读内容?

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?

推荐答案

在这种情况下使用的模式是使用 BeginRead 来读取流(就像您正在做的那样)并处理流中的更多数据"回调方法中的案例.
回调方法调用 EndRead 并收集从流中读取的数据(通常通过将其附加到 StringBuilder 实例)然后再次调用 BeginRead.一旦 EndRead 返回 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

我注意到那里没有特别说明 0 字节返回是保证,所以我理解你在这里的困惑,但这个例子很清楚,这是你停止阅读的信号.

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.

这篇关于.NET NetworkStream 关​​闭,如何确保读取所有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆