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
| <?php namespace App\Console;
use think\console\Command; use think\console\Input; use think\console\Output;
class AsyncTask extends Command { protected $server; protected function configure() { $this->setName('task:start')->setDescription('Start TCP(Timer) Server!'); } protected function execute(Input $input, Output $output) { $this->server = new \swoole_server("0.0.0.0", 9501); $this->server->set([ 'worker_num' => 4, 'daemonize' => false, 'task_worker_num' => 4 ]); $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->start(); } public function onStart(\swoole_server $server) { echo "开始\n"; } public function onConnect(\swoole_server $server, $fd, $from_id) { echo "连接上了\n"; } public function onReceive(\swoole_server $server, $fd, $from_id, $data) { $task_id = $server->task($data); $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}, 任务处理 \n"; $server->finish("$data -> OK"); } public function onFinish(\swoole_server $server, $task_id, $data) { echo "结束"; } public function onClose(\swoole_server $server, $fd, $from_id) { echo "结束\n"; } }
|