1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| namespace app\Console;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class AsyncTask extends Command
{
protected $server;
// 命令行配置函数
protected function configure()
{
// setName 设置命令行名称
// setDescription 设置命令行描述
$this->setName('task:start')->setDescription('Start Task Server!');
}
// 设置命令返回信息
protected function execute(Input $input, Output $output)
{
$this->server = new \swoole_server('0.0.0.0', 9509);
// server 运行前配置
$this->server->set([
'worker_num' => 4,
'daemonize' => false,
'task_worker_num' => 4 # task 进程数
]);
// 注册回调函数
$this->server->on('Start', [$this, 'onStart']);
$this->server->on('Connect', [$this, 'onConnect']);
$this->server->on('Receive', [$this, 'onReceive']);
$this->server->on('Task', [$this, 'onTask']);
$this->server->on('Finish', [$this, 'onFinish']);
$this->server->on('Close', [$this, 'onClose']);
$this->server->on('Message', [$this, 'onMessage']);
$this->server->start();
}
// 主进程启动时回调函数
public function onStart(\swoole_server $server)
{
echo "Start\n";
}
// 建立连接时回调函数
public function onConnect(\swoole_server $server, $fd, $from_id)
{
echo "$fd 连接了\n";
}
// 收到信息时回调函数
public function onReceive(\swoole_server $server, $fd, $from_id, $data)
{
echo $data.PHP_EOL;
//print_r($data);
// 投递异步任务
//$task_id = $server->task($data);
// echo "Dispath AsyncTask: id={$task_id}\n";
// 将受到的客户端消息再返回给客户端
// $server->send($fd, "Message form Server: {$data}, task_id: {$task_id}");
}
// 异步任务处理函数
public function onTask(\swoole_server $server, $task_id, $from_id, $data)
{
echo "{$task_id}, Task Completed \n";
//返回任务执行的结果
$server->finish("$data -> OK");
}
// 异步任务完成通知 Worker 进程函数
public function onFinish(\swoole_server $server, $task_id, $data)
{
echo "AsyncTask[{$task_id}] Finish: {$data} \n";
}
// 关闭连时回调函数
public function onClose(\swoole_server $server, $fd, $from_id)
{
echo "Close\n";
}
public function onMessage($server, $frame)
{
echo $frame->data.PHP_EOL;
}
}
|