zoukankan      html  css  js  c++  java
  • swoole通过websocket进行消息推送

    laravel 之 swoole

    <?php
    
    namespace AppConsoleCommands;
    
    use IlluminateConsoleCommand;
    use IlluminateSupportFacadesRedis;
    use phpDocumentorReflectionTypesNull_;
    
    class Swoole extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'swoole:action {action}';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'swoole command';
    
        /**
         * @var Message
         */
        protected $message;
    
        /**
         * @var User
         */
        protected $user;
    
        /**
         * @var Room
         */
        protected $room;
    
        private $server;
        private $fid=[];
    
        /**
         * Swoole constructor.
         * @param Message $message
         * @param User $user
         * @param RoomJoin $room
         */
        public function __construct( )
        {
            parent::__construct();
        }
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $action = $this->argument('action');
            switch ($action) {
                case 'start':
                    $this->start();
                    break;
                case 'stop':
                    $this->stop();
                    break;
                case 'restart':
                    $this->restart();
                    break;
            }
        }
    
        /**
         * 开启websocket
         */
        private function start()
        {
            $this->server = new swoole_websocket_server(config("swoole.host"), config("swoole.port"), SWOOLE_BASE, SWOOLE_SOCK_TCP);
            //SWOOLE_SSL  需要ssl才加
            #监听WebSocket连接打开事件
            $this->server->on('open', function ($server, $request) {
                // 验证链接
                $fdinfo = $this->server->getClientInfo($request->fd);
                if($fdinfo['remote_ip'] != '127.0.0.1' && $fdinfo['server_port'] != '9502')
                    return;
                $this->server->push($request->fd, '["pang"]');
                // 验证链接
                $fdinfo = $this->server->getClientInfo($request->fd);
                if($fdinfo['remote_ip'] != '127.0.0.1' && $fdinfo['server_port'] != '9502')
                    return;
                $this->fid[]=$request->fd;   # $request->fd fd
            });
            #监听WebSocket消息事件
            $this->server->on('message', function ($server, $frame) {   #$frame->data 消息内容
                $msg = 'from' . $frame->fd . ":{$frame->data}
    ";
                Log::info("message :".$msg);
    //            if($frame->data != 'pings') return;
                // 验证链接
                $fdinfo = $this->server->getClientInfo($frame->fd);
                if($fdinfo['remote_ip'] != '127.0.0.1' && $fdinfo['server_port'] != '9502')
                    return;
                foreach ($this->fid as $fd) {
                    $server->push($fd, $msg);
                }
                Log::info("fds :".json_encode($this->fid));
            });
    
            //监听WebSocket连接关闭事件
            $this->server->on('close', function($ws, $fd) {
                // 验证链接
                $fdinfo = $this->server->getClientInfo($fd);
                if($fdinfo['remote_ip'] != '127.0.0.1' && $fdinfo['server_port'] != '9502')
                    return;
                Log::info("client info:".json_encode($fdinfo));
                Log::info("list fd:".json_encode($this->fid));
                $fd_key = array_search($fd, $this->fid ? $this->fid : []);
                $key_zero = isset($this->fid[0]) && $this->fid[0] == $fd ? TRUE : FALSE;  # key=0
                if ($fd_key || $key_zero) {
                    unset($this->fid[$fd_key]);
                }
                Log::info("client-{$fd} is closed
    ");
            });
    
            #onRequest回调    http://127.0.0.1:9502/?sendto=1,20,3&message=%E4%BD%A0%E5%A5%BD
            $this->server->on('request', function ($req, $respone) {
                // 验证链接
                $fdinfo = $this->server->getClientInfo($respone->fd);
                if($fdinfo['remote_ip'] != '127.0.0.1' && $fdinfo['server_port'] != '9502')
                    $respone->end("404 not found");
                # get 两个参数, userid ","  发送消息
                $list=[];
                if (isset($req->get['message'])) {
                    $list = $this->fid;
                    if (!empty($list)) {
                        foreach ($list as $fd) {
                            $this->server->push($fd, $req->get['message']);
                        }
                    }
                }
    
                $total= count($this->fid);
                $sendSum= count($list);
                $respone->end("Current fid:{$respone->fd},  OnLine:{$total}, Send:{$sendSum}");
    
            });
    
            $this->server->start();
        }
    
        /**
         * 停止websocket
         */
        private function stop()
        {
    
        }
    
        /**
         * 重启
         */
        private function restart()
        {
    
        }
    
    
    }
  • 相关阅读:
    go包之logrus显示日志文件与行号
    linux几种快速清空文件内容的方法
    (转)CSS3之pointer-events(屏蔽鼠标事件)属性说明
    Linux下source命令详解
    控制台操作mysql常用命令
    解决beego中同时开启http和https时,https端口占用问题
    有关亚马逊云的使用链接收集
    favicon.ico--网站标题小图片二三事
    js获取url协议、url, 端口号等信息路由信息
    (转) Golang的单引号、双引号与反引号
  • 原文地址:https://www.cnblogs.com/akidongzi/p/10419889.html
Copyright © 2011-2022 走看看