<strong>第一部分定时器写法</strong>
swoole_timer_tick函数就相当于setInterval,是持续触发的
swoole_timer_after函数相当于setTimeout,仅在约定的时间触发一次
swoole_timer_tick/swoole_timer_after函数会返回一个整数,表示定时器的ID
可以使用 swoole_timer_clear 清除此定时器,参数为定时器ID 说明客户端断开连接不会影响定时器
<?php//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, "hello, welcome/n");
});//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}/n";
$ws->push($frame->fd, "server: {$frame->data}");
});//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed/n";
});
//定时器要写在WorkerStart这个里面哦
$ws->on('WorkerStart', function ($serv, $worker_id){
//3000ms后执行此函数
$aaa=swoole_timer_tick(2000, function ($timer_id) {
echo "tick-2000ms/n";
});
echo $aaa.'/n';
//清除定时器
// swoole_timer_clear($aaa);
});$ws->start();
<strong>使用迭代器遍历Server所有连接</strong>
<?php//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
foreach($ws->connections as $fd)
{
$ws->push($request->fd, "hello, welcome1/n");}
//获取连接总数
echo '获取所有链接数'.count($ws->connections).'/n';
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}/n";
$ws->push($frame->fd, "server: {$frame->data}");
});//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed/n";
});
$ws->start();
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/19162.html