美文网首页php知识总结程序员
swoole websocket 主动推送消息

swoole websocket 主动推送消息

作者: 响呼雷 | 来源:发表于2020-01-07 09:40 被阅读0次

    先来说一下,我非常的开森,终于搞定啦,哈哈哈!!!

    既然你搜到了这篇文章,那么你肯定已经安装过了环境(及时没安装,这里也认为你已经安装完成),哈哈哈

    我这里有两个方案:直接上代码

    一、第一种方式

    server.php

    $server = new \Swoole\WebSocket\Server("0.0.0.0", 9501);
    
    $server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
        echo "server: handshake success with fd{$request->fd}\n";
    });
    
    $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $server->push($frame->fd, "this is server");
    });
    
    $server->on("request", function(swoole_http_request $request, swoole_http_response $response) use($server){
        //遍历所有WebSocket连接用户的fd,给所有用户推送
        global $server;
        foreach ($server->connections as $fd) {
            // 需要先判断是否是正确的websocket连接,否则有可能会push失败
            if ($server->isEstablished($fd)) {
                $server->push($fd, $request->post['scene']);
            }
        }
    });
    
    $server->on('close', function ($ser, $fd) {
        echo "client {$fd} closed\n";
    });
    
    $server->start();
    

    client.php

    class pc{
        public function curl($data)
        {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, "http://127.0.0.1:9501");
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_HEADER, 1);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_exec($curl);
            curl_close($curl);
        }
    
        /**
         * 主动触发
         */
        public function activepush()
        {
            $param['scene'] = '主动推送消息';
            $this->curl($param);   // 主动推送消息
        }
    }
    
    $obj = new pc();
    $obj->activepush();
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="msg"></div>
    <input type="text" id="text">
    <input type="submit" value="发送数据" onclick="song()">
    </body>
    <script>
        var msg = document.getElementById("msg");
        var wsServer = 'ws://******:9501';
        //调用websocket对象建立连接:
        //参数:ws/wss(加密)://ip:port (字符串)
        var websocket = new WebSocket(wsServer);
        //onopen监听连接打开
        websocket.onopen = function (evt) {
            msg.innerHTML = websocket.readyState;
        };
    
        function song(){
            var text = document.getElementById('text').value;
            document.getElementById('text').value = '';
            //向服务器发送数据
            websocket.send(text);
        }
        //监听连接关闭
        websocket.onclose = function (evt) {
            console.log("Disconnected");
        };
    
        //onmessage 监听服务器数据推送
        websocket.onmessage = function (evt) {
            msg.innerHTML += evt.data +'<br>';
    //        console.log('Retrieved data from server: ' + evt.data);
        };
        //监听连接错误信息
        websocket.onerror = function (evt, e) {
            console.log('Error occured: ' + evt.data);
        };
    
    </script>
    </html>
    

    这个方法主要通过curl触发了swoole的onRequest方法,你在onRequest里可以获取到所有的请求信息,然后获取到相应的消息内容,消息会显示到indnx.html页面上

    二、第二种方式

    server.php

    $server = new \Swoole\WebSocket\Server("0.0.0.0", 9501);
    
    $server->on('open', function (\Swoole\WebSocket\Server $server, $request) {
        echo "server: handshake success with fd{$request->fd}\n";
    });
    
    $server->on('message', function (\Swoole\WebSocket\Server $server, $frame) {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $server->push($frame->fd, "this is server");
    });
    
    $process = new \Swoole\Process(function ($process)use($server) {
        echo 'process';
        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->auth('xiaocinao');
        $redis->subscribe(['name'],function ($redis,$channel,$msg)use($server){
            $server->push(1,$msg);
        });
    });
    
    $server->on("request", function(swoole_http_request $request, swoole_http_response $response) use($server){
        print_r($request);
    });
    
    $server->on('close', function ($ser, $fd) {
        echo "client {$fd} closed\n";
    });
    $server->addProcess($process);
    $server->start();
    

    你会发现和第一种方法多了\Swoole\Process,这里是开一个进程来订阅redis的

    client.php

    $redis = new \Redis();
    $redis->connect('127.0.0.1',6379);
    $redis->auth('xiaocinao');
    $redis->publish('name',11111222222);
    

    index.html

    和第一种方法一样
    

    大功告成!!!!!赶集你测试去吧!

    相关文章

      网友评论

        本文标题:swoole websocket 主动推送消息

        本文链接:https://www.haomeiwen.com/subject/zzfractx.html