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
| <?php namespace app\Console; use think\console\Command; use think\console\Input; use think\console\Output; class Timer extends Command { protected $server; protected function configure() { $this->setName('timer: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, ]); $this->server->on('Start', [$this, 'onStart']); $this->server->on('WorkerStart', [$this, 'onWorkerStart']); $this->server->on('Connect', [$this, 'onConnect']); $this->server->on('Receive', [$this, 'onReceive']); $this->server->on('Close', [$this, 'onClose']); $this->server->start(); } public function onStart(\swoole_server $server) { echo "Start" . PHP_EOL; } public function onWorkerStart(\swoole_server $server, $worker_id) { if ($worker_id == 0) { swoole_timer_tick(1000, [$this, 'onTick']); } } public function onTick($timer_id, $params = null) { echo 'Hello' . PHP_EOL; } public function onConnect(\swoole_server $server, $fd, $from_id) { echo "Connect" . PHP_EOL; } public function onReceive(\swoole_server $server, $fd, $from_id, $data) { echo "message: {$data} form Client: {$fd}" . PHP_EOL; $server->send($fd, "Message form Server: ".$data); } public function onClose(\swoole_server $server, $fd, $from_id) { echo "Close" . PHP_EOL; } }
|