swoole-framwork/core/server/HttpServer.php

82 lines
2.7 KiB
PHP
Raw Normal View History

2024-05-20 11:51:07 +08:00
<?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' => 1, //设置启动的 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']);
}
public function onWorkerStart(Server $server,int $workerId)
{
//cli_set_process_title("ttt worker"); //设置进程名称
//把index文件里的代码搬过来
\Core\BeanFactory::init();
$this->dispatcher = \Core\BeanFactory::getBean('RouterCollector')->getDispatcher();
}
public function onStart(Server $server)
{
$mid = $server->master_pid; //返回当前服务器主进程的 PID。
file_put_contents("./ttt.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("./ttt.pid");
}
public function run()
{
$p = new TestProcess();
//$this->server->addProcess($p->run());
echo '就要启动了';
$this->server->start();
}
}