【thinkphp5+swoole赛事直播教程系列9】task任务使用

<?php
/**
 * Created by PhpStorm.
 * User: rocky
 * Date: 18-9-19
 * Time: 上午7:43
 */
class Ws
{
    const HOST = "0.0.0.0";
    const PORT = 9501;
    public  $ws = null;

    public function __construct()
    {
        $this->ws = new swoole_websocket_server("0.0.0.0",9501);
        $this->ws->set([
            'worker'=>2,
            'task_worker_num'=>2,
            'enable_static_handler'=>true,
            'document_root'=>'/home/rocky/www/assets',
        ]);
        $this->ws->on('open',[$this,'onOpen']);
        $this->ws->on('message',[$this,'onMessage']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onClose']);
        $this->ws->start();
    }

    public function onOpen($ws,$request)
    {
        var_dump($request->fd);
    }

    public function onMessage($ws,$frame)
    {
        echo "server push message:{$frame->data}\n";
        $data = [
            'task'=>1,
            'fd'=>$frame->fd,
        ];
        $ws->task($data);
        $ws->push($frame->fd,"server-push:".date('Y-m-d H:i:s'));
    }

    public function onTask($serv,$taskId,$workerId,$data)
    {
        print_r($data);
        sleep(10);
        return "task finish";
    }

    public function onFinish($serv,$taskId,$data)
    {
        echo "taskId:{$taskId}\n";
        echo "finish data success:{$data}\n";
    }

    public function onClose($ws,$fd)
    {
        echo "client-{$fd} closed";
    }


}
$obj = new Ws();

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/82768663