onMessage收不到客户端发送的信息之后,onWorkerStart中的$connection为空无法触发foreach一下的判断,有没有大佬能帮忙看看!!感谢您了
<?php
require_once __DIR__ . '/Workerman/Autoloader.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
// 心跳间隔55秒
define('HEARTBEAT_TIME', 55);
$worker = new Worker('http://0.0.0.0:8687');
$worker->onMessage = function($connection, $msg) {
// 给connection临时设置一个lastMessageTime属性,用来记录上次收到消息的时间
$connection->lastMessageTime = time();
// 其它业务逻辑...
// echo $connection->id;
echo "上线";
};
// 进程启动后设置一个每秒运行一次的定时器
$worker->onWorkerStart = function($worker) {
var_dump($worker->connections);
Timer::add(1, function()use($worker){
$time_now = time();
echo "||".$time_now."||";
// var_dump($connection);
foreach($worker->connections as $connection) {
echo "标志1";
// var_dump($worker->connections);
$jicheng = $connection;
echo($jicheng ->id);
// 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间
echo $jicheng->lastMessageTime;
if (empty($jicheng->lastMessageTime)) {
$jicheng->lastMessageTime = $time_now;
continue;
}
// 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接
if ($time_now - $jicheng->lastMessageTime > HEARTBEAT_TIME) {
// $connection->close();
echo "下线";
}
}
});
};
Worker::runAll();
1个回答
年代过于久远,无法发表回答
没有客户端连接的话,$worker->connections为空数组是正常的