swoole server task任务执行完触发onfinish回调,如何返回值给用户?

  1. 当在swoole httpServer的worker中执行task异步任务时,执行完毕后想给用户返回信息,该如何发送消息给用户呢?
阅读 492
评论 2019-09-30 提问
    1 个回答
    宇润
    • 693

    这个是协程挂起,等待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();
    评论 赞赏
      撰写回答

      登录后参与交流、获取后续更新提醒