当前位置:  首页博文详情

thinkphp+swoole+websocket实时更新服务端数据

宁夏 2020年3月15日 398 阅读

  1. 添加自定义命令行

<?php
return [
    'app\queen\command\Serve'
];

2.自定义命令行内容

<?php

namespace app\queen\command;

use app\common\model\Photo;
use think\console\Command;
use think\console\Input;
use think\console\Output;

define('HOST', '0.0.0.0');
define('PORT', '9501');
define('WORKER_NUM', 8);
define('DISPATCH_MODE', 2);
define('DAEMONIZE', 0);

class Serve extends Command
{
    protected $server;
    protected $dn = 0;

    protected function configure()
    {
        $this->setName('serve')->setDescription('Serve');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->server = new \swoole_websocket_server(HOST, PORT);
        $this->server->set(
            [
                'worker_num' => WORKER_NUM,//开启woker进程数
                'dispatch_mode' => DISPATCH_MODE, //请求分发策略,
                'daemonize' => DAEMONIZE,  //是否守护进程
            ]
        );
        $this->server->on('message', [$this, 'onMessage']);
        $this->server->on('open', [$this, 'onOpen']);
        $this->server->on('workerStart', [$this, 'onWorkerStart']);
        $this->server->start();

    }

    //woker进程
    public function onWorkerStart(\swoole_websocket_server $server, $worker_id)
    {
        if ($worker_id == 0) {
            $this->server->tick(3000, [$this, 'onTick']);
        }
    }

    //接受客户端数据
    public function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame)
    {
        echo $frame->data;
        echo $server->worker_id;
    }

    //客户端 服务端建立连接并完成握手后的回调
    public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
    {
        dump($request);
        $this->update();
    }

    private function update()
    {
        if ($this->dn > 1000)
            $this->dn = 0;

        echo 'index:' . $this->dn . PHP_EOL;

        $data = Photo::order('id','asc')->page(++$this->dn,1)->selectOrFail()->toArray();
        //向所有客户端发送数据
        foreach ($this->server->connections as $connection) {
            $this->server->push($connection, json_encode($data));
        }
    }

    //定时器回调
    public function onTick()
    {
        echo date('s-');
        $this->update();
    }
}

3.前端测试页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>swoole websocket tick test</title>
    <link type="text/css" href="./css/login.css">
    <style>
        .img-box {width: 640px;line-height: 880px;overflow: hidden;margin: 0 auto;position: fixed;top: 20px;left: 20px;right: 20px;bottom: 20px;align-items: center;}
        #img {width:100%}
    </style>
</head>
<body style="background:#000">
<div class="img-box">
    <img id="img" src='{:setting("default_img",3)}'>
</div>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</body>
</html>
<script>
    $(".admin-ty").click(function () {
        $(this).siblings().removeClass('admin-ty-active');
        $(this).addClass('admin-ty-active')
    });
    if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");

        var ws = new WebSocket("ws://39.154.0.175:9501");
        ws.onopen = function () {
            ws.send("发送数据");
            console.log("数据发送中...");
        };

        ws.onmessage = function (e) {
            var data = JSON.parse(e.data);
            console.log(data)
            data.forEach(function(row){
                console.log(row.origin)
                $("#img").attr('src',row.origin)
            })

        };

        ws.onclose = function () {
            console.log("连接已关闭...");
        };
    }
    else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!");
    }
</script>


上一篇: Linux安装第三方PHP扩展

下一篇: 没有了

相关文章

标签云

站点信息

  • 文章统计:11 篇
  • 标签统计:3 个