客户端连接断开时的 NetworkStream.BeginRead

发布于 2024-11-07 13:09:43 字数 590 浏览 3 评论 0原文

我有一个 TCP 客户端流,正在通过异步调用 NetworkStream.BeginRead (传递异步回调委托)读取。问题是检测连接何时断开。目前,如果连接被切断,BeginRead 调用就会消失在以太中 - 回调不会被调用。如果应用程序在流关闭时尝试在流上发送,确实会触发回调,并且 NetworkStream.EndRead 会引发异常 - 这没问题 - 但如果没有发出发送,那么应用程序就会处于黑暗中而不自知。该连接已断开。

最初我看到 NetworkStream.ReadTimout 没有设置(即默认的 Timout.Infinite) - 但设置它(例如,3000ms)并没有帮助。 异步 BeginRead - 我应该更早地更仔细地检查:-( ]

如何检测客户端连接失败?

[编辑:MSDN 文档明确指出 ReadTimeout 仅适用于同步 Read 调用,而不适用于 我必须轮询底层套接字,如这个SO问题所示?

另外:当物理上重新建立连接时,回调仍然存在不接到电话 - 我们只是坐在以太中等待,直到我们尝试发送。

Ive got a TCP client stream that is being read via async call NetworkStream.BeginRead (passing an async call back delegate). The problem is to detect when the connection is down. Currently if the connection is cut the BeginRead call just disappears into the ether - the call back is just not called. If the app try a send on the stream while its down this does trigger the callback and NetworkStream.EndRead throws an exception - this is OK - but if no send is issued then app just sits in the dark unware that connection is down.

Initially I saw that NetworkStream.ReadTimout was not set (i.e. was default Timout.Infinite) - but setting this (to, say, 3000ms) didn't help. [Edit: MSDN doc clearly states that ReadTimeout only applys to the syncronous Read call not the asyn BeginRead - I should have checked that more carefully earlier :-( ]

How to detect that client connection has failed?

Do I have to poll the underlying socket as shown in this SO question?

In addition: When the connection is physically re-established the callback still doesn't get called - we just sit waiting in the ether until we try a send.

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

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

发布评论

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

评论(1

记忆里有你的影子 2024-11-14 13:09:43

我最终不得不从 TcpClient 异步 BeginRead 更改为同步 Read,并在专用读取 Thead 上超时。

这使我能够在由于流上没有数据而导致超时时引发事件。

I ended up having to change from a TcpClient async BeginRead to a syncronous Read with a timeout on a dedicated read Thead.

This enabled me to raise an event when the timeout was pulled due to no data on the stream.

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