套接字心跳与保活

Socket heartbeat vs 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 行为可移植到各种操作系统并在所有操作系统上保持一致,那么滚动您自己的心跳通常是可行的方法.

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.

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

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).

这篇关于套接字心跳与保活的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:套接字心跳与保活

基础教程推荐