Why is the heartbeat necessary?

Almost all online game servers have a heartbeat package (HeartBeat or Ping) design. In the recent development of mobile game servers, the heartbeat package is also used. Thinking about thinking, is the heartbeat bag necessary? Why do I need a heartbeat package? Does TCP not provide a method for disconnection detection? Can the KeepAlive mechanism provided by TCP replace HeartBeat?

由于连接丢失时,TCP不会立即通知应用程序。 For example, if the client program is disconnected, the TCP connection of the server will not be detected as disconnected, but will remain connected.这就带来了很大的麻烦,明明客户端已经断了,服务端还维护着客户端的连接,照常执行着该玩家的游戏逻辑……

心跳包就是用来及时检测是否A mechanism of disconnection is to detect whether the other party is connected by sending heartbeat data every certain time interval. It is part of the application protocol.

问题1: TCP为什么不自己提供断线检测?

首先,断线检测需要轮询发送检测报文,会消耗一定的网络带宽和暂用一定的网络资源。 If it is made into the underlying default function of TCP, those applications that do not require disconnection detection will waste unnecessary bandwidth resources.

另外,TCP不提供连接丢失及时通知的最重要原因与其主要设计目的目标之一有关:出现网络故障时维护通信的能力。 TCP is a research sponsored by the US Department of Defense. It is a network protocol that can maintain reliable network communications even in the event of serious network damage such as war or natural disasters. Usually, the network failure is only temporary, and sometimes the router will silently reconnect after the temporary TCP connection is lost. Therefore, TCP itself does not provide such timely disconnection detection.

问题2: TCP的KeepAlive机制可以用来及时检测连接状态吗?

TCP有个KeepAlive开关,打开后可以用来检测死连接。 Usually the default is 2 hours, you can set it yourself. But note that this is a global setting of TCP. If in order to detect the disconnected connection more timely, the time of tcp_keepalive_time and tcp_keepalive_intvl is reduced (reference: Link), the KeepAlive detection interval of all applications on the machine will be reduced, which is obviously unacceptable. Because the needs of different applications are different.

(在某些平台的Socket实现已经支持为每条连接单独设置KeepAlive参数)

KeepAlive本质上来说,是用来检测长时间不活跃的连接的。 Therefore, it is not suitable for detecting the connection status in time.

问题3:心跳包(HeartBeat)为什么是好的方式及时检测连接状态?

1. 具有更大的灵活性,可以自己控制检测的间隔,检测的方式等等。

2. The heartbeat packet is applicable to both TCP and UDP. When switching between TCP and UDP, the upper layer heartbeat packet function is applicable. (In fact, this kind of situation is rarely encountered)

3. In some cases, the heartbeat package can be accompanied by some other information, which is regularly in the service Synchronization between the client and the client. (For example, frame synchronization)

Leave a Comment

Your email address will not be published.