一、代码

<?php

/**
 * 面向对象的形式 + task + timer
 */
class WebsocketTest
{
    public $server;

    public function __construct()
    {
        $this->server = new Swoole\WebSocket\Server("0.0.0.0", 9502);
        $this->server->set([
            'worker_num' => 2,
            'task_worker_num' => 2
        ]);
        $this->server->on('open', [$this, 'onOpen']);
        $this->server->on('message', [$this, 'onMessage']);
        $this->server->on('task', [$this, 'onTask']);
        $this->server->on('finish', [$this, 'onFinish']);
        $this->server->on('close', [$this, 'onClose']);
        $this->server->start();
    }

    public function onOpen(swoole_websocket_server $server, $request)
    {
        echo "server: handshake success with fd{$request->fd}".PHP_EOL;
        // 每隔多少时间执行
        if ($request->fd == 1) {
            swoole_timer_tick(2000, function ($timer_id) {
                echo '2s: timerId:'.$timer_id.PHP_EOL;
            });
        }
    }

    /**
     * 监听我是消息事件
     *
     * @param Swoole\WebSocket\Server $server
     * @param [type] $frame
     * @return void
     */
    public function onMessage(Swoole\WebSocket\Server $server, $frame)
    {
        echo "receive from {$frame->fd}:{$frame->data}, opcode:{$frame->opcode}, fin:{$frame->finish}".PHP_EOL;
        // 投放一个 异步 onTask任务 todo 20s
        $data = [
            'task' => 1,
            'fd' => $frame->fd,
        ];
        $server->task($data);
        // 指定的时间后执行 比下面的push后执行(异步)
        swoole_timer_after(20000, function () use ($server, $frame) {
            $server->push($frame->fd, "task finished ".date('Y-m-d H:i:s'));
        });
        // 返回给客户端信息
        $server->push($frame->fd, "this is server ".date('Y-m-d H:i:s'));
    }

    /**
     * @param swoole_server $serv
     * @param [type] $task_id
     * @param [type] $src_worker_id
     * @param [type] $data
     * @return void
     */
    public function onTask(swoole_server $serv, $task_id, $src_worker_id, $data)
    {
        print_r($data);
        // 耗时场景
        sleep(20);
        // 告诉worker
        return 'after 20 seconds, on task finish';
    }

    public function onFinish($serv, $task_id, $data)
    {
        echo 'taskId:'.$task_id.PHP_EOL;
        // onTask 返回的内容
        echo 'finish data:'.$data;
    }
    
    public function onClose($ser, $fd)
    {
        echo "client {$fd} closed\n";
    }
}

new WebsocketTest();

客户端用的还是原来的 ws_client.html

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄