swoole之任務和定時器

1、代碼php

<?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;
    }

    /**
     * 監聽我是消息事件
     *
     * @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;
        $data = [
            'task' => 1,
            'fd' => $frame->fd,
        ];
        // 投放一個 異步 onTask任務 todo 10s
        $server->task($data);
        // 開始一個定時任務 每隔多少時間執行
        if ($frame->fd == 1) {
            swoole_timer_tick(2000, function ($timer_id) {
                echo '2s: timerId:'.$timer_id.PHP_EOL;
            });
        }
        // 指定的時間後執行 比下面的push後執行(異步)10s
        swoole_timer_after(10000, 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);
        echo 'task start:'.date("Y-m-d H:i:s").PHP_EOL;
        // 模擬耗時場景
        sleep(10);
        // onFinsh 告訴worker
        return "after 10 seconds, on task finish\n";
    }

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

new WebsocketTest();

 

 

 

客戶端用的仍是原來的 ws_client.htmlhtml

相關文章
相關標籤/搜索