swoole-task

PHP技术
526
0
0
2022-11-02
标签   Swoole

耗时的一些操作,邮件、公告之类的,

<?php
class Ws{
    const HOST ="127.0.0.1";
    const PORT = 9504;
    public $ws;

    public function __construct() {
        $this->ws = new swoole_websocket_server("0.0.0.0", self::PORT);
        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => '/home/malina/project/swoole/static',
            'worker_num' => 2,
            'task_worker_num' => 2,
        ]);
        $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){
        print_r($request->fd);
    }

    public function onMessage($ws, $frame) {
        echo "ser-push-msg:{$frame->data}\n";
        //todo 10s 
        $data = [
            'task' => 1,
            'fd' => $frame->fd
        ];
        $ws->task($data);
        $ws->push($frame->fd, "sev-push:".date("Y-md H:i:s"));
    }

    public function onTask($serv, $task_id, $reactor_id, $data){
        print_r($data);
        //耗时场景 
        sleep(10);
        return "on task finish";
    }

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

    public function onClose($ws, $fd) {
        echo "client:{$fd}\n";
    }
}

$obj = new Ws();