Home >PHP Framework >Workerman >How to use workerman's heartbeat
Gateway/Worker development model supports server-side heartbeat detection, which can regularly send application-layer heartbeats to the client, and can promptly detect extreme client disconnections (power outages) , sudden network failure, etc.).
Note: Long connection applications must add heartbeat, otherwise the connection may be forcibly disconnected by the routing node due to no communication for a long time. (Recommended learning: workerman tutorial)
The heartbeat has two main functions:
1. The client regularly sends point data to the server. Prevent the connection from being closed by the firewall of some nodes due to no communication for a long time, causing the connection to be disconnected.
2. The server can determine whether the client is online through heartbeat. If the client does not send any data within the specified time, the client is considered offline. This can detect events where the client goes offline due to extreme circumstances (power outage, network disconnection, etc.).
Heartbeat interval recommended value:
It is recommended that the client sends a heartbeat interval of less than 60 seconds, such as 55 seconds.
Example:
<?php require_once __DIR__ . '/Workerman/Autoloader.php'; use Workerman\Worker; use Workerman\Lib\Timer; // 心跳间隔55秒 define('HEARTBEAT_TIME', 55); $worker = new Worker('text://0.0.0.0:1234'); $worker->onMessage = function($connection, $msg) { // 给connection临时设置一个lastMessageTime属性,用来记录上次收到消息的时间 $connection->lastMessageTime = time(); // 其它业务逻辑... }; // 进程启动后设置一个每秒运行一次的定时器 $worker->onWorkerStart = function($worker) { Timer::add(1, function()use($worker){ $time_now = time(); foreach($worker->connections as $connection) { // 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间 if (empty($connection->lastMessageTime)) { $connection->lastMessageTime = $time_now; continue; } // 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接 if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) { $connection->close(); } } }); }; Worker::runAll();
The above configuration is that if the client does not send any data to the server for more than 55 seconds, the server will think that the client has been offline. Close the connection and trigger onClose.
The above is the detailed content of How to use workerman's heartbeat. For more information, please follow other related articles on the PHP Chinese website!