server = new Server($this->host,$this->port); echo 'host: http://' . $this->host . ':' . $this->port . PHP_EOL; //配置参数 https://wiki.swoole.com/#/server/setting $this->server->set(array( 'worker_num' => 2, //设置启动的 Worker 进程数。【默认值:CPU 核数】 'daemonize' => false // 使用docker 不需要设置守护进程 )); //$this->server->on('request',function ($req,$res){}); $this->server->on('Request', [$this, 'onRequset']); $this->server->on('Start', [$this, 'onStart']); $this->server->on('ShutDown', [$this, 'onShutDown']); $this->server->on('WorkerStart',[$this,'onWorkerStart']); $this->server->on('ManagerStart', [$this,"onManagerStart"]); } public function onWorkerStart(Server $server,int $workerId) { //cli_set_process_title('baihand worker');//设置进程名称 \Core\BeanFactory::init(); $this->dispatcher = \Core\BeanFactory::getBean('RouterCollector')->getDispatcher(); } public function onManagerStart(Server $server) { //cli_set_process_title('baihand manger'); } public function onStart(Server $server) { //cli_set_process_title('baihand manger'); $mid = $server->master_pid; //返回当前服务器主进程的 PID。 file_put_contents("./Buddha.pid", $mid); //会覆盖 } public function onRequset($request, $response) { $myRequest = \Core\http\Request::init($request); $myResponse = \Core\http\Response::init($response); $routeInfo = $this->dispatcher->dispatch($myRequest->getMethod(),$myRequest->getUri()); switch($routeInfo[0]) { case \FastRoute\Dispatcher::NOT_FOUND: $response->status(404); $response->write(json_encode(['code' => 404, 'msg' => 'NOT_FOUND'])); $response->end(); break; case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $response->status(405); $response->write(json_encode(['code' => 405, 'msg' => 'METHOD_NOT_ALLOWED'])); $response->end(); break; case \FastRoute\Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2];//参数 $extVars = [$myRequest, $myResponse]; //$response->end($handler($vars, $extVars)); $myResponse->setBody($handler($vars,$extVars)); $myResponse->end(); break; } } public function onShutDown(Server $server) { echo '关闭了' . PHP_EOL; unlink("./Buddha.pid"); } public function run() { //$p = new TestProcess(); //$this->server->addProcess($p->run()); echo '就要启动了喂......' . PHP_EOL; $this->server->start(); } }