Files
kiri-core/http-server/Events/OnReceive.php
T

87 lines
1.5 KiB
PHP
Raw Normal View History

2020-08-31 01:27:08 +08:00
<?php
namespace HttpServer\Events;
2020-09-02 11:38:47 +08:00
use HttpServer\Events\Abstracts\Callback;
2020-08-31 01:27:08 +08:00
use Snowflake\Core\JSON;
use Snowflake\Event;
use Snowflake\Snowflake;
use Swoole\Server;
2020-09-02 11:38:47 +08:00
use Exception;
use Closure;
2020-08-31 01:27:08 +08:00
/**
2020-09-02 11:38:47 +08:00
* Class OnReceive
2020-08-31 01:27:08 +08:00
* @package HttpServer\Events
*/
2020-09-02 11:38:47 +08:00
class OnReceive extends Callback
2020-08-31 01:27:08 +08:00
{
2020-09-02 11:38:47 +08:00
/** @var Closure|array */
public $unpack;
/** @var Closure|array */
public $pack;
/**
* @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 int $fd
* @param int $reactorId
* @param string $data
* @return mixed
* @throws Exception
*/
2020-09-02 11:38:47 +08:00
public function onHandler(\Swoole\Server $server, int $fd, int $reactorId, string $data)
2020-08-31 01:27:08 +08:00
{
try {
$client = [$fd];
if (empty($data = $this->unpack($data))) {
throw new Exception('Format error.');
}
$client[] = $this->pack($data);
return $server->send(...$client);
} catch (\Throwable $exception) {
$client[] = $this->pack(['message' => $exception->getMessage()]);
return $server->send(...$client);
} finally {
$event = Snowflake::get()->event;
$event->trigger(Event::SERVER_WORKER_STOP);
}
}
}