86 lines
2.9 KiB
PHP
86 lines
2.9 KiB
PHP
<?php
|
||
|
||
namespace Core\server;
|
||
|
||
use Swoole\Http\Server;
|
||
use Core\init\TestProcess;
|
||
class HttpServer
|
||
{
|
||
private $server;
|
||
private $dispatcher;
|
||
|
||
public function __construct($str = 'dd')
|
||
{
|
||
if ($str == 'dd') return;
|
||
$this->server = new Server("0.0.0.0",8085);
|
||
//配置参数 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->end();
|
||
break;
|
||
case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
|
||
$response->status(405);
|
||
$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();
|
||
}
|
||
} |