php 如何实现心跳
PHP 实现心跳机制的方法
心跳机制通常用于保持客户端与服务器之间的长连接,避免因超时而断开。以下是几种常见的实现方式:
使用 AJAX 轮询
客户端通过 JavaScript 定时向服务器发送请求,服务器返回响应以维持连接。
// 服务器端代码(heartbeat.php)
header('Content-Type: application/json');
echo json_encode(['status' => 'alive']);
// 客户端代码
setInterval(function() {
fetch('heartbeat.php')
.then(response => response.json())
.then(data => console.log(data));
}, 30000); // 每30秒发送一次心跳
使用 WebSocket
WebSocket 提供了全双工通信通道,适合实时性要求高的场景。
// 使用 Ratchet 库实现 WebSocket 服务器
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Heartbeat implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {}
public function onClose(ConnectionInterface $conn) {}
public function onError(ConnectionInterface $conn, \Exception $e) {}
public function onMessage(ConnectionInterface $from, $msg) {
$from->send('pong');
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new Heartbeat())),
8080
);
$server->run();
使用长轮询(Long Polling)
服务器在有数据时返回响应,否则保持连接直到超时。
// 服务器端代码(longpolling.php)
$timeout = 30;
$startTime = time();
while (true) {
if (time() - $startTime > $timeout) {
echo json_encode(['status' => 'timeout']);
break;
}
usleep(100000); // 减少 CPU 占用
}
注意事项
- 心跳间隔应根据实际需求调整,过短会增加服务器负担,过长可能导致连接超时。
- WebSocket 需要服务器支持,适合高性能场景。
- 对于简单的应用,AJAX 轮询或长轮询是更简单的选择。







