参考文献
client同步阻塞客户端:https://wiki.swoole.com/#/client?id=完整示例
heartbeat_check_interval:https://wiki.swoole.com/#/server/setting?id=heartbeat_check_interval
健康检查机制
对于长连接这种断开的问题;主要的点就在于服务端会保存客户端会话的有效性以及平台上监控所有客户端的网络状况;对于这种功能的实现我们可以通过两种方式实现
1、轮询机制
2、心跳机制
代码演示
tcpServer.php
<?php
// var_dump(swoole_get_local_ip());die;
echo swoole_get_local_ip()['eth0'].":9503\n";
$server = new Swoole\Server("0.0.0.0", 9503);
// 每个2s检测,在3s内没有给我发送信息的连接
$server->set([
'heartbeat_check_interval' => 2, // 检测所有的连接
'heartbeat_idle_time' => 3,
]);
$server->on('connect', function ($server, $fd){
echo "connection open: {$fd}\n";
});
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
echo "接收到信息".$data." \n";
$server->send($fd, "swoole: {$data}");
});
$server->on('close', function ($server, $fd) {
echo "connection close: {$fd}\n";
});
$server->start();
tcpClient.php
<?php
$client = new Swoole\Client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9503, -1)) {
exit("connect failed. Error: {$client->errCode}\n");
}
# 初始测试
// $client->send("hello world1\n");
// echo $client->recv();
// sleep(2);
// $client->send("hello world2\n");
// echo $client->recv();
// sleep(3);
// $client->send("hello world3\n");
// echo $client->recv();
// sleep(4);
// $client->send("hello world4\n");
// echo $client->recv();
// $client->close();
// 本文采用此方法解决
// 每隔2000ms触发一次
swoole_timer_tick(2000, function ($timer_id) use ($client) {
echo "string\n";
$client->send(1);
$client->recv();
});
$client->close();