好记性不如铅笔头

编程

TCP keepalive 简单笔记

本文参考
https://www.jianshu.com/p/e3791f975d7b
http://www.blogjava.net/yongboy/archive/2015/04/14/424413.html
https://blog.csdn.net/lanyang123456/article/details/90578453

SO_KEEPALIVE的定义

SO_KEEPALIVE用于开启或者关闭保活探测,默认情况下是关闭的。
当SO_KEEPALIVE开启时,可以保持连接检测对方主机是否崩溃,避免(服务器)永远阻塞于TCP连接的输入。

相关的属性包括:

tcp_keepalive_intvl (integer; default: 75; since Linux 2.4)
      The number of seconds between TCP keep-alive probes.

tcp_keepalive_probes (integer; default: 9; since Linux 2.2)
      The maximum number of TCP keep-alive probes to send before
      giving up and killing the connection if no response is
      obtained from the other end.

tcp_keepalive_time (integer; default: 7200; since Linux 2.2)
      The number of seconds a connection needs to be idle before TCP
      begins sending out keep-alive probes.  Keep-alives are sent
      only when the SO_KEEPALIVE socket option is enabled.  The
      default value is 7200 seconds (2 hours).  An idle connection
      is terminated after approximately an additional 11 minutes (9
      probes an interval of 75 seconds apart) when keep-alive is
      enabled.

      Note that underlying connection tracking mechanisms and
      application timeouts may be much shorter.

在 socket 编程中,我们对指定的 socket 添加 SO_KEEPALIVE 这个 option,这个 socket 便可以启用 KeepAlive 功能。以Linux系统为例,描述下过程和相关参数:
连接闲置 tcp_keepalive_time 秒后,发送探测包,如果对方回应ACK,便认为依然在线;否则间隔 tcp_keepalive_intvl 秒后,持续发送探测包,一直到发送了 tcp_keepalive_probes 个探测包后,还未得到ACK回馈,便认为对方crash了。

常见的几种使用场景:
检测挂掉的连接(导致连接挂掉的原因很多,如服务停止、网络波动、宕机、应用重启等)。
防止因为网络不活动而断连(使用NAT代理或者防火墙的时候,经常会出现这种问题)。
TCP层面的心跳检测。

KeepAlive通过定时发送探测包来探测连接的对端是否存活,但通常也会在应用层面处理心跳:
TCP自带的KeepAlive使用简单,发送的数据包相比应用层心跳检测包更小,仅提供检测连接功能
应用层心跳包不依赖于传输层协议,无论传输层协议是TCP还是UDP都可以用。
应用层心跳包可以定制,可以应对更复杂的情况或传输一些额外信息。
KeepAlive仅代表连接保持着,而心跳包往往还代表客户端可正常工作。

发表评论

5 × 2 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据