套接字心跳与Keepalive [英] Socket heartbeat vs keepalive

查看:102
本文介绍了套接字心跳与Keepalive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现自己的心跳并为套接字设置Keepalive的利弊是什么?

What are pros and cons for implementing own heartbeat and setting`keepalive for a socket?

我在某处读到,keepalive有时可能会失败,并且无论如何连接都会关闭(取决于网络结构)。另一件事是,自己的心跳可以检测应用程序是否响应(不仅是套接字)。

I read somewhere, that keepalive sometimes can fail and connection will be closed anyway (depends on network structure). Another thing is that own heartbeat can detect if application is responsive (not only the socket).

我的主要目标是确保所有这些:即使没有数据发送(保持可能的心跳),连接也保持活动状态;双方的快速连接丢失检测,应用程序响应度检测。

My main goal is to ensure all of these: keep connection alive, even though no data is send (beside possible heartbeat), fast connection loss detection on both sides, application responsiveness detection.

我已经在两端实现了一个简单的心跳,并且效果很好,但是我想知道是否可以用现成的keepalive功能代替它。

I have already implemented a simple heartbeat on two ends and it works great, however I wonder if maybe I could replace it with out of the box keepalive feature.

推荐答案

TCP内置的keepalive功能的一个问题是它并不总是易于配置的。例如,在Linux上,setsockopt()有多种选项(例如TCP_KEEPIDLE,TCP_KEEPCNT和TCP_KEEPINTVL),可用于将keepalive的行为设置为所需的行为,但是。因此,如果您希望程序的keepalive行为可移植到各种OS并在所有OS上始终保持一致,则滚动自己的心跳通常是可行的方法。

One problem with TCP's built in keepalive feature is that it's not always easily configurable. For example, on Linux there are various options to setsockopt() (e.g. TCP_KEEPIDLE, TCP_KEEPCNT, and TCP_KEEPINTVL) that you can use to set the keepalive's behavior to what you want, but in other OS's those behaviors are not easily adjusted, at least not programmatically. So if you want your program's keepalive behavior to be portable to various OS's and behave consistently on all of them, rolling your own heartbeat is generally the way to go.

另一方面,可能有一些程序或网络协议不容易支持心跳/无操作消息的概念(或者您可能希望您的程序能够使用许多协议,而不必提出这些协议每种支持的协议使用单独的Keepalive逻辑),在这种情况下,您可能要使用内置的keepalive,因为它具有发送和接收不影响TCP数据流内容的透明 keepalive数据包的能力。在这种情况下,内置的keepalive可能会有用(特别是如果您只需要在Linux下运行keepalive代码)。

On the other hand, there may be some programs or network protocols out there that don't easily support the concept of a heartbeat/no-op message (or you might want your program to be able to use many protocols, without having to come up with separate keepalive logic for every supported protocol), and in that case you might want to use the built-in keepalive because it has the ability to send and receive "transparent" keepalive packets that do not affect the contents of the TCP data stream. In that case, the built-in keepalive can be useful (especially if you only really need the keepalive code to work under Linux).

这篇关于套接字心跳与Keepalive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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