如何检测套接字连接何时丢失? [英] How to detect when socket connection is lost?

查看:150
本文介绍了如何检测套接字连接何时丢失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本(我目前没有这里的代码示例,但是我使用了IO :: Async),它连接到远程服务器上的socket并监听。客户端通常只是侦听新数据。

I have a script (I don't have the code example here at the moment but I used IO::Async) which connects to socket on a remote server and listens. Client usually just listens for new data.

问题是客户端无法检测网络问题是否发生以及套接字连接是否消失。
我使用IO :: Async,我也尝试使用IO :: Socket。初始连接建立后,句柄始终处于连接状态。

Problem is that the client is not able to detect if network problems occur and the socket connection is gone. I used IO::Async and I also tried it with IO::Socket. Handle is always "connected" after the initial connection is established.

如果再次建立网络连接,套接字连接自然会丢失,因为脚本不知道它应该重新连接。

If the network connection is established again the socket connection is naturally still lost because the script has no idea that it should reconnect.

我正在考虑创建某种keepAlive,每隔X秒ping(syswrite)套接字(如果没有新的东西通过套接字)来检查连接是否仍然存在。

I was thinking to create some kind of "keepAlive" which "pings" (syswrite) the socket every X seconds (if nothing new came through socket) to check whether the connection is still there.

这是正确的方法,还是可能有另一个更有创意或更清洁的解决方案?

Is this the correct way to do it or is there maybe an another more creative or cleaner solution?

推荐答案

您可以设置 SO_KEEPALIVE 套接字选项,对于TCP,它会发送定期的keepalive消息,并可能有助于检测此情况。如果检测到这种情况,您将收到一个EOF条件(最有可能导致包含 IO :: Async :: Stream 来触发 on_read_eof )。

You can set the SO_KEEPALIVE socket option which, for TCP, sends periodic keepalive messages, and may help detect this condition. If this is detected, you will be delivered an EOF condition (most likely causing the containing IO::Async::Stream to fire on_read_eof).

为了获得更好的解决方案,您可以考虑使用某种应用程序级别的keepalive消息,例如IRC的 PING 命令。

For a better solution you might consider some sort of application-level keepalive message, such as IRC's PING command.

这篇关于如何检测套接字连接何时丢失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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