«

webman/push 统计在线人数

时间:2024-4-30 14:13     作者:杨佳乐     分类: PHP


自定义进程定时获取在线人数广播给所有在线用户
process/Status.php

<?php

namespace process;

use app\Request;
use Webman\Push\Api;
use Workerman\Timer;
use Workerman\Worker;
use think\facade\Db;

class Status
{
    public function __construct()
    {
        Timer::add(3, function () {
            $this->status();
        });
    }

    public function status()
    {
        static $user_count = 0, $page_count = 0;
        $api = new Api(
            'http://127.0.0.1:3232',
            config('plugin.webman.push.app.app_key'),
            config('plugin.webman.push.app.app_secret')
        );
        $result = $api->get('/channels', ['filter_by_prefix' => 'user', 'info' => 'subscription_count']);
        if (!$result || $result['status'] != 200) {
            return;
        }
        $channels = $result['result']['channels'];
        $user_count_now = count($channels);
        $page_count_now = 0;
        foreach ($channels as $channel) {
            $page_count_now += $channel['subscription_count'];
        }
        if ($page_count_now == $page_count && $user_count_now === $user_count) {
            return;
        }
        $user_count = $user_count_now;
        $page_count = $page_count_now;

        $api->trigger('online-page', 'update_online_status', "当前<b>$user_count</b>人在线,共打开<b>$page_count</b>个页面");
    }
}

自定义进程配置文件
config/process.php

<?php
use Workerman\Worker;
return [
    // ...其它配置...

    'status'  => [
        'handler'  => process\Status::class
    ]
];

前端js代码

var connection = new Push({
    url: 'wss://xxx.com',
    app_key: 'xxxx',
});
function update_online_status(status) {
    $('#online_status').html(status);
}
var online_channel = connection.subscribe('online-page');
online_channel.on('update_online_status', update_online_status);
var user_channel = connection.subscribe('user-<?=session()->getId()?>');
user_channel.on('update_online_status', update_online_status);

以上是实现类似workerman站点底部实时在线统计的代码