0
  1. 当在swoole httpServer的worker中执行task异步任务时,执行完毕后想给用户返回信息,该如何发送消息给用户呢?
sowork 187
2019-09-30 提问
1 个回答
0

已采纳

这个是协程挂起,等待task执行完毕,再执行输出。如果你需要用户不等待task,需要用websocket,而不是http

<?php
class Test
{
    private $server;

    public function run()
    {
        $this->server = new Swoole\Http\Server("127.0.0.1", 9501);
        $this->server->set([
            'task_worker_num'   =>  4,
        ]);
        $this->server->on('request', function ($request, $response) {
            $action = $request->get['action'];
            $result = $this->server->taskwait($action);
            $response->end($result);
        });
        $this->server->on('task', function($serv, $task_id, $from_id, $data){
            switch($data)
            {
                case 'a':
                    $return = 1;
                    break;
                case 'b':
                    $return = 2;
                    break;
                default:
                    $return = '???';
            }
            $this->server->finish('action:' . $data . ', result:' . $return);
        });
        $this->server->start();
    }
}
$test = new Test;
$test->run();

撰写答案

推广链接