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

66 lines
1.4 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-08-31 01:27:08 +08:00
namespace HttpServer\Events;
2021-04-07 14:15:50 +08:00
use Exception;
2020-09-04 01:05:33 +08:00
use HttpServer\Abstracts\Callback;
2021-03-08 16:01:07 +08:00
use Snowflake\Core\Json;
2020-08-31 01:27:08 +08:00
use Snowflake\Event;
use Snowflake\Snowflake;
use Swoole\Server;
/**
* Class OnPacket
2020-09-02 11:38:47 +08:00
* @package HttpServer\Events
2020-08-31 01:27:08 +08:00
*/
2020-09-02 11:38:47 +08:00
class OnPacket extends Callback
2020-08-31 01:27:08 +08:00
{
2020-09-02 11:38:47 +08:00
2021-03-08 16:01:07 +08:00
public int $port = 0;
2020-09-02 11:38:47 +08:00
2021-03-08 16:01:07 +08:00
public string $host = '';
2020-09-02 11:38:47 +08:00
2020-08-31 01:27:08 +08:00
/**
* @param Server $server
* @param $data
* @param $clientInfo
* @return mixed
2020-11-01 04:47:05 +08:00
* @throws Exception
2020-08-31 01:27:08 +08:00
*/
2020-12-17 14:09:14 +08:00
public function onHandler(Server $server, string $data, array $clientInfo): mixed
2020-08-31 01:27:08 +08:00
{
2021-04-07 14:15:50 +08:00
[$host, $port] = [$clientInfo['address'], $clientInfo['port']];
2020-08-31 01:27:08 +08:00
try {
2021-04-23 03:25:03 +08:00
defer(function () {
2021-04-07 14:15:50 +08:00
fire(Event::SYSTEM_RESOURCE_RELEASES);
});
$request = $this->_request($clientInfo, $server, $data);
2021-03-08 16:01:07 +08:00
$router = Snowflake::app()->getRouter();
if (($node = $router->find_path($request)) === null) {
return $server->sendto($host, $port, Json::encode(['state' => 404]));
2020-08-31 01:27:08 +08:00
}
2021-03-08 16:33:10 +08:00
$dispatch = $node->dispatch();
if (!is_string($dispatch)) $dispatch = Json::encode($dispatch);
2021-04-01 11:28:42 +08:00
if (empty($dispatch)) {
2021-04-01 11:43:24 +08:00
$dispatch = Json::encode(['state' => 0, 'message' => 'ok']);
2021-04-01 11:28:42 +08:00
}
2021-03-08 16:33:10 +08:00
return $server->sendto($host, $port, $dispatch);
2020-08-31 01:27:08 +08:00
} catch (\Throwable $exception) {
2021-03-08 18:40:42 +08:00
$this->addError($exception, 'packet');
2021-03-08 16:01:07 +08:00
$response = Json::encode(['state' => 500, 'message' => $exception->getMessage()]);
2021-04-07 14:15:50 +08:00
return $server->sendto($host, $port, $response);
2020-08-31 01:27:08 +08:00
}
}
2020-09-02 11:38:47 +08:00
2020-08-31 01:27:08 +08:00
}