Home  >  Article  >  Backend Development  >  Use workerman to count the number of people online on the website in real time under ThinkPHP6

Use workerman to count the number of people online on the website in real time under ThinkPHP6

幸运切糕
幸运切糕Original
2020-05-02 19:30:28147browse

Workerman is an open source, high-performance PHP socket server framework developed purely in PHP. It is widely used in the development of mobile apps, mobile game servers, online game servers, chat room servers, hardware communication servers, smart homes, Internet of Vehicles, Internet of Things and other fields. Supports TCP long connections, supports Websocket, HTTP and other protocols, and supports custom protocols. Based on Workerman, developers can focus more on business logic development and no longer have to worry about the underlying development of PHP Socket.

This article introduces in detail the method of using composer to install the workerman extension under tp6 to achieve real-time statistics of the number of people online.


##Install think-worker extension

For the installation method, please refer to the official manual of thinkphp6:

composer installation

composer require topthink/think-worker


Create workerman service class

Create class file

app/common/http/Worker.php<span style="background-color: rgb(255, 255, 255); color: rgb(88, 96, 105); font-family: -apple-system, BlinkMacSystemFont, " segoe ui helvetica arial sans-serif color emoji font-size:></span>

<?php

namespace app\common\http;

use think\worker\Server;
use Workerman\Lib\Timer;
use think\facade\Cache;

class Worker extends Server
{
        //监听7373端口
        protected $socket = &#39;http://0.0.0.0:7373&#39;;
    //在线人数,初始为0
    protected $connection_count = 0;
    
    public function __construct(){
    	parent::__construct();
    }

    public function onConnect($connection)
    {
        //客户端连接成功,在线人数+1
        ++$this->connection_count;
    }
 
    public function onWorkerStart($worker)
    {
        //定时器,每隔1秒执行一次,根据自己需求修改
        Timer::add(1, function() use($worker){
            $data = json_encode([
                &#39;online&#39;    => $this->connection_count,
            ]);
            //把最新的在线人数循环推送给已连接的客户端
            foreach($worker->connections as $connection){
                $connection->send($data);
            }
            //缓存最新在线人数,页面渲染时,会先从缓存中读取,提高用户体验
            Cache::set(&#39;online&#39;, $this->connection_count);
        });
    }

    public function onClose($connection)
    {
        //客户端断开,在线人数-1
        $this->connection_count--;
    }

    public function onError($connection, $code, $msg){}
}


<span style="background-color: rgb(255, 255, 255); color: rgb(88, 96, 105); font-family: -apple-system, BlinkMacSystemFont, " segoe ui helvetica arial sans-serif color emoji font-size:></span>#Modify the worker configuration fileOpen config\worker_server.php, the parts that need to be changed are as follows:

&#39;worker_class&#39;   => &#39;app\common\http\Worker&#39;, // 自定义Workerman服务类名 支持数组定义多个服务


##Controller test code

<?php
namespace app\controller;

use app\BaseController;
use think\facade\View;

class Index extends BaseController
{
    public function index()
    {
        return View::fetch();
    }
}


##View test code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>workerman实时统计在线人数测试</title>
</head>
<body>

    <div>
        <span>在线人数:</span>
        <span id="online">{$online}</span>
    </div>

    {load href="/static/js/jquery.min.js}
    <script>
        ws = new WebSocket("ws://localhost:7373");
        ws.onmessage = function(e) {
            var data = JSON.parse(e.data);
            $(&#39;#online&#39;).text(data.online + &#39; 人&#39;);
        }
    </script>

</body>
</html>


##Start workererman

Go to the project root directory and execute the following command:

php think worker:server


Verify statistical results

Use workerman to count the number of people online on the website in real time under ThinkPHP6

##The statistics are successful. Let’s open another window to see if the number of people will increase?

OK, the latest number of people has been automatically refreshed to the page. Friends, the more you practice, the more impressive the impression will be. This ends the tutorial. I hope you like it!

The above are the details of using workerman to count the number of people online on the website in real time under ThinkPHP6. For more information, please pay attention to other related articles on the PHP Chinese website!

The above is the detailed content of Use workerman to count the number of people online on the website in real time under ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn