swoole websocket_task

 2,    //worker process num
        'task_worker_num' => 2,    //worker process num
        'document_root' => '/home/season/Desktop/swoole/demo/temp',
        'enable_static_handler' => true,
    ];

    public function __construct()
    {
        $this->sw = new swoole_websocket_server(self::HOST, self::PORT);
        $this->sw->set($this->set);
        $this->sw->on('open', [$this, 'onOpen']);
        $this->sw->on('message', [$this, 'onMessage']);
        $this->sw->on('task', [$this, 'onTask']);
        $this->sw->on('finish', [$this, 'onFinish']);
        $this->sw->on('close', [$this, 'onClose']);
        $this->sw->start();
    }

    //监听websocket 打开/连接 事件
    //当WebSocket客户端与服务器建立连接并完成握手后会回调此方法。
    public function onOpen($server, $request)
    {
        echo "服务器: 握手成功,fd{$request->fd}\n";
    }

    //当WebSocket客户端与服务器建立连接并完成握手后会回调此函数。
    public function onMessage($server, $frame)
    {
        echo "收到 {$frame->fd}:{$frame->data},操作码:{$frame->opcode},完成:{$frame->finish}\n";

        $data = [
            'task' => 1,
            'fd' => $frame->fd,
        ];
        $server->task($data);


        $redisClient = new Swoole\Redis();
        $redisClient->connect('127.0.0.1',6379,function (swoole_redis $swoole_redis ,$result)use ($frame) {
            $swoole_redis->set($frame->fd,true,function (swoole_redis $swoole_redis,$result){});

            $swoole_redis->keys('*',function (swoole_redis $swoole_redis,$result) use($frame){
                print_r($result);

                foreach ($result as $fd) {
                    $this->sw->push($fd, '用户'.$frame->fd.'已登录');
                }
            });
        });

    }

    //任务
    public function onTask($server, $task_id, $src_worker_id, $data)
    {
        //print_r($data);
        $data['msg'] = '任务完成';
        sleep(10);

        return json_encode($data);
    }

    /**
     * @param $server
     * @param $task_id 任务的ID
     * @param $data onTask return返回的数据
     */
    public function onFinish($server, $task_id, $data)
    {
        $data = json_decode($data);
        //echo "任务编号:{$task_id},{$data->msg}\n";
        $server->push($data->fd, "任务编号:{$task_id},{$data->msg}\n");
    }

    //关闭时出发回调
    public function onClose($server, $fd)
    {
        echo "客户端: {$fd} 已关闭\n";
    }
}

new SW();




    
    swoole-websocket






swoole websocket_task_第1张图片
服务器
swoole websocket_task_第2张图片
浏览器

swoole websocket_task_第3张图片
浏览器

你可能感兴趣的:(swoole websocket_task)