代码如下
<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
require_once __DIR__ . '/Workerman/Autoloader.php';
// 初始化一个worker容器,监听1234端口
$worker = new Worker('websocket://127.0.0.1:1234');
// ====这里进程数必须必须必须设置为1====
$worker->count = 1;
// 新增加一个属性,用来保存uid到connection的映射(uid是用户id或者客户端唯一标识)
$worker->uidConnections = array();
$worker->meet_time=array();
$worker->meet_id=array();
$worker->onConnect = function($connection)
{
// 有新的客户端连接时,连接数+1
global $connection_count;
++$connection_count;
echo "now connection_count=$connection_count\n";
};
// 进程启动后设置一个每秒运行一次的定时器
$worker->onWorkerStart = function($worker) {
Timer::add(15, function()use($worker){
$time_now = time();
//按会议循环获取会议时长
foreach($worker->meet_time as $k=>$v){
$play_total_time=0;
foreach ($v as $k2=>$v2){
if($v2['e']==0){
$play_total_time=$play_total_time+(time()-$v2['b']);
}else{
$play_total_time=$play_total_time+($v2['e']-$v2['b']);
}
}
//计算剩余时长
$play_sul_time=$worker->meet_id[$k]['time']-$play_total_time;
//向直播页面发送剩余直播时长
$n_time=date("Y-m-d H:i:s");
$worker->meet_id[$k]['con']->send($n_time."--剩余时长--".$play_sul_time);
}
});
};
// 当有客户端发来消息时执行的回调函数
$worker->onMessage = function($connection, $data)
{
global $worker;
// 判断当前客户端是否已经验证,即是否设置了uid
if(!isset($connection->uid))
{
$connection->uid =$connection->id;
$connection->lastMessageTime = time();
//list($name, $meet_id) = explode(':', $data);
$arr=json_decode($data);
if($arr[0]=='play'){
$worker->meet_time[$arr[1]]=array($connection->uid=>array('b'=>$connection->lastMessageTime,'e'=>0));
$worker->uidConnections[$connection->uid] = $connection;
}else if($arr[0]=='live'){
$worker->meet_id[$arr[1]]['con']=$connection;
$worker->meet_id[$arr[1]]['time']=$arr[2];
$n_time=date("Y-m-d H:i:s");
$worker->meet_id[$arr[1]]['con']->send($n_time."--剩余时长--".$arr[2]);
}
$connection->clientType=$arr[0];
$connection->m_id=$arr[1];
}
};
// 当有客户端连接断开时
$worker->onClose = function($connection)
{
global $worker;
if(isset($connection->uid))
{
global $connection_count;
$connection_count--;
$now_time=time();
if($connection->clientType=='play'){
$worker->meet_time[$connection->m_id][$connection->uid]['e']=$now_time;
$sul_time=$now_time-$connection->lastMessageTime;
file_put_contents(__DIR__."/log.txt",'client['.$connection->uid.']已下线。总计'.$sul_time.'>>>开始时间'.$connection->lastMessageTime.'结束时间'.$now_time.PHP_EOL,FILE_APPEND);
}
// 连接断开时删除映射
unset($worker->uidConnections[$connection->uid]);
}
};
// 运行所有的worker(其实当前只定义了一个)
Worker::runAll();