swoole-framwork/core/server/HttpServer.php
2024-06-26 17:13:45 +08:00

88 lines
3.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Core\server;
use Swoole\Http\Server;
use Core\init\TestProcess;
use Core\BeanFactory;
#[Injectable(lazy: true)]
class HttpServer
{
private $server;
private $dispatcher;
private $host = 'localhost';
private $port = 8086;
public function __construct($daemonize = false)
{
$this->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' => 4, //设置启动的 Worker 进程数。【默认值CPU 核数】
'daemonize' => $daemonize //设置守护进程
));
$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(true);
$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();
}
}