Files
kiri-core/HttpServer/Events/OnClose.php
T

102 lines
2.0 KiB
PHP
Raw Normal View History

2020-09-02 11:38:47 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-09-02 11:38:47 +08:00
namespace HttpServer\Events;
2020-12-15 14:04:02 +08:00
use Annotation\Route\Socket;
2020-09-04 01:05:33 +08:00
use HttpServer\Abstracts\Callback;
2021-03-03 14:10:53 +08:00
use HttpServer\Http\Request;
2020-09-02 11:38:47 +08:00
use Snowflake\Event;
2020-11-27 14:57:58 +08:00
use Snowflake\Exception\ComponentException;
2021-03-03 14:10:53 +08:00
use Snowflake\Exception\ConfigException;
use Snowflake\Exception\NotFindClassException;
2020-09-02 11:38:47 +08:00
use Snowflake\Snowflake;
use Swoole\Server;
use Exception;
2021-03-05 14:55:50 +08:00
use Swoole\WebSocket\Server as WebsocketServer;
2020-09-02 11:38:47 +08:00
/**
* Class OnClose
* @package HttpServer\Events
2020-11-06 16:48:57 +08:00
*
2020-09-02 11:38:47 +08:00
*/
class OnClose extends Callback
{
/**
* @param Server $server
* @param int $fd
* @throws Exception
*/
public function onHandler(Server $server, int $fd)
2020-11-27 14:57:58 +08:00
{
2021-03-08 18:40:42 +08:00
try {
$this->execute($server, $fd);
} catch (\Throwable $exception) {
$this->addError($exception);
} finally {
fire(Event::SYSTEM_RESOURCE_RELEASES);
logger()->insert();
}
2020-11-27 14:57:58 +08:00
}
/**
* @param Server $server
* @param int $fd
* @throws ComponentException
* @throws Exception
*/
2020-12-15 14:04:02 +08:00
private function execute(Server $server, int $fd): void
2020-09-02 11:38:47 +08:00
{
2021-03-08 18:40:42 +08:00
if (!$this->isWebsocket($server, $fd)) {
$client = $server->getClientInfo($fd);
fire($this->name($client['server_port']), [$server, $fd]);
} else {
$this->loadNode($server, $fd);
2020-09-02 11:38:47 +08:00
}
}
2021-03-03 14:10:53 +08:00
2021-03-08 18:29:59 +08:00
/**
* @param $server_port
* @return string
*/
private function name($server_port): string
{
2021-03-08 18:33:55 +08:00
return 'listen ' . $server_port . ' ' . Event::SERVER_CLIENT_CLOSE;
2021-03-08 18:29:59 +08:00
}
/**
* @param $server
* @param $fd
* @return bool
*/
private function isWebsocket($server, $fd): bool
{
return $server instanceof WebsocketServer && $server->isEstablished($fd);
}
2021-03-03 14:10:53 +08:00
/**
* @param $server
* @param $fd
* @return mixed
* @throws ComponentException
* @throws ConfigException
* @throws NotFindClassException
* @throws Exception
*/
private function loadNode($server, $fd): mixed
{
$query = Request::socketQuery((object)['fd' => $fd], Socket::CLOSE);
if (($node = router()->find_path($query)) !== null) {
return $node->dispatch($server, $fd);
}
return null;
}
2020-09-02 11:38:47 +08:00
}