当前位置: 代码迷 >> 综合 >> swoole_server-task
  详细解决方案

swoole_server-task

热度:84   发布时间:2023-10-20 08:19:35.0

简介

投递一个异步任务到task_worker池中。此函数是非阻塞的,执行完毕会立即返回。Worker进程可以继续处理新的请求。使用Task功能,必须先设置 task_worker_num,并且必须设置Server的onTask和onFinish事件回调函数。

https://wiki.swoole.com/wiki/page/134.html

代码

Server

<?php class Server {
     private $serv;public function __construct(){
     $this->serv = new swoole_server('127.0.0.1', 9501);//注意这里要用多进程模式,不填写默认是多进程$this->serv->set(array('worker_num' => 4,'daemonize' => false,'backlog' => 128,'dispatch_mode' => 5,'task_worker_num'=>4));$this->serv->on('Connect', array($this,'onConnect'));$this->serv->on('Receive', array($this,'onReceive'));$this->serv->on('Close', array($this,'onClose'));$this->serv->on('Task', array($this,'onTask'));$this->serv->on('Finish', array($this,'onFinish'));$this->serv->start();}public function onConnect(swoole_server $server, int $fd, int $reactorId){
      print_r($fd."--连接上了\n"); }public function onReceive(swoole_server $server, int $fd, int $reactor_id, string $data){
     print_r("主进程\n");$server->task($data); $start_fd = 0;while(true){$conn_list = $server->getClientList($start_fd, 10);if ($conn_list===false or count($conn_list) === 0){echo "finish\n";break;}$start_fd = end($conn_list);var_dump($conn_list);foreach($conn_list as $fd){$server->send($fd, "群发消息");}}}public function onClose(swoole_server $server, int $fd, int $reactorId){
     print_r($fd."--关闭了连接\n");}public function onTask(swoole_server $server, int $task_id, int $src_worker_id, $data){
     echo "我是task回调\n";//返回任务执行的结果$server->finish("finish");}public function onFinish(swoole_server $serv, int $task_id, string $data){
     echo "我是finish回调";} }new Server(); 

Client

<?php $client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1))
{exit("connect failed. Error: {
    $client->errCode}\n");
}
$client->send("task");while ($as = $client->recv()) {print_r($as."\n");
}

结果

swoole_server-task

swoole_server-task

  相关解决方案