php 实现心跳
PHP 实现心跳机制的方法
心跳机制通常用于维持长连接或检测客户端是否在线。以下是几种常见的实现方式:
使用 AJAX 轮询
客户端定期向服务器发送请求,服务器返回响应表示连接正常。

// 服务器端 heartbeat.php
header('Content-Type: application/json');
echo json_encode(['status' => 'alive', 'timestamp' => time()]);
// 客户端 JavaScript
setInterval(function() {
fetch('heartbeat.php')
.then(response => response.json())
.then(data => console.log(data));
}, 30000); // 每30秒发送一次
WebSocket 心跳
对于 WebSocket 连接,可以通过定时发送消息实现心跳。

// WebSocket 服务器示例(使用 Ratchet 库)
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Heartbeat implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn) {
// 新连接
}
public function onMessage(ConnectionInterface $conn, $msg) {
// 处理消息
if ($msg === 'PING') {
$conn->send('PONG');
}
}
// ...其他方法
}
数据库记录心跳
通过定期更新数据库中的时间戳来跟踪活动状态。
// 更新心跳时间戳
function updateHeartbeat($userId) {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->prepare("UPDATE users SET last_heartbeat = NOW() WHERE id = ?");
$stmt->execute([$userId]);
}
文件锁机制
使用文件系统记录最后一次活动时间。
function checkHeartbeat($clientId) {
$file = "/tmp/heartbeat_{$clientId}.lock";
touch($file); // 更新文件修改时间
// 检查是否超时(30秒无心跳)
if (time() - filemtime($file) > 30) {
return false; // 心跳超时
}
return true;
}
注意事项
- 心跳间隔应根据实际需求设置,太短会增加服务器负载,太长会影响实时性
- 对于大量连接的情况,建议使用更高效的方案如Redis
- 需要考虑网络延迟和时钟同步问题
- 心跳超时后应有相应的重连或清理机制






