TCP keep-alive 以确定客户端是否在 netty 中断开连接 [英] TCP keep-alive to determine if client disconnected in netty

查看:49
本文介绍了TCP keep-alive 以确定客户端是否在 netty 中断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定客户端是否已关闭来自 netty 的套接字连接.有没有办法做到这一点?

I'm trying to determine if a client has closed a socket connection from netty. Is there a way to do this?

推荐答案

在客户端通过 close() 关闭套接字并且 TCP 关闭握手成功完成的通常情况下,channelInactive()(或channelClosed() in 3)事件将被触发.

On a usual case where a client closes the socket via close() and the TCP closing handshake has been finished successfully, a channelInactive() (or channelClosed() in 3) event will be triggered.

但是,在不寻常的情况下,例如客户端计算机由于停电或 LAN 电缆拔掉而离线,您可能需要很长时间才能发现连接实际上已关闭.要检测这种情况,您必须定期向客户端发送一些消息,并期望在一定时间内收到其响应.这就像一个 ping - 你应该在你的协议中定义一个周期性的 ping 和 pong 消息,它实际上除了检查连接的健康之外什么都不做.

However, on an unusual case such as where a client machine goes offline due to power outage or unplugged LAN cable, it can take a lot of time until you discover the connection was actually down. To detect this situation, you have to send some message to the client periodically and expect to receive its response within a certain amount of time. It's like a ping - you should define a periodic ping and pong message in your protocol which practically does nothing but checking the health of the connection.

或者,您可以启用SO_KEEPALIVE,但此选项的保活时间间隔通常取决于操作系统,我不建议使用它.

Alternatively, you can enable SO_KEEPALIVE, but the keepalive interval of this option is usually OS-dependent and I would not recommend using it.

为了帮助用户相对容易地实现这种行为,Netty 提供了 ReadTimeoutHandler.配置您的管道,以便 ReadTimeoutHandler 在一段时间内没有入站流量时引发异常,并在您的 exceptionCaught() 处理程序方法中关闭异常连接.如果您是应该发送定期 ping 消息的一方,请使用计时器(或 IdleStateHandler)发送.

To help a user implement this sort of behavior relatively easily, Netty provides ReadTimeoutHandler. Configure your pipeline so that ReadTimeoutHandler raises an exception when there's no inbound traffic for a certain amount of time, and close the connection on the exception in your exceptionCaught() handler method. If you are the party who is supposed to send a periodic ping message, use a timer (or IdleStateHandler) to send it.

这篇关于TCP keep-alive 以确定客户端是否在 netty 中断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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