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

87 lines
1.5 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;
2020-09-02 11:38:47 +08:00
use Closure;
2020-09-04 01:05:33 +08:00
use HttpServer\Abstracts\Callback;
2020-09-02 11:38:47 +08:00
use Snowflake\Core\JSON;
2020-08-31 01:27:08 +08:00
use Snowflake\Event;
use Snowflake\Snowflake;
use Swoole\Server;
2020-09-02 11:38:47 +08:00
use Exception;
2020-08-31 01:27:08 +08:00
/**
* 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
2020-11-01 03:54:09 +08:00
/** @var ?Closure */
public ?Closure $unpack = null;
2020-09-02 11:38:47 +08:00
2020-11-01 03:54:09 +08:00
/** @var ?Closure */
public ?Closure $pack = null;
2020-09-02 11:38:47 +08:00
/**
* @param $data
* @return mixed
* @throws Exception
*/
public function pack($data)
{
$callback = $this->pack;
if (is_callable($callback, true)) {
return $callback($data);
}
return JSON::encode($data);
}
/**
* @param $data
* @return mixed
*/
public function unpack($data)
{
$callback = $this->unpack;
if (is_callable($callback, true)) {
return $callback($data);
}
return JSON::decode($data);
}
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-11-01 04:47:05 +08:00
public function onHandler(Server $server,string $data,array $clientInfo)
2020-08-31 01:27:08 +08:00
{
try {
$client = [$clientInfo['address'], $clientInfo['port']];
if (empty($data = $this->unpack($data))) {
throw new Exception('Format error.');
}
$client[] = $this->pack($data);
return $server->sendto(...$client);
} catch (\Throwable $exception) {
$client[] = $this->pack(['message' => $exception->getMessage()]);
return $server->sendto(...$client);
} finally {
2020-09-03 11:39:20 +08:00
$event = Snowflake::app()->event;
2020-08-31 01:27:08 +08:00
$event->trigger(Event::SERVER_WORKER_STOP);
}
}
2020-09-02 11:38:47 +08:00
2020-08-31 01:27:08 +08:00
}