This commit is contained in:
2020-11-04 19:28:40 +08:00
parent dc2216a8b9
commit d533102a77
4 changed files with 124 additions and 69 deletions
+6 -34
View File
@@ -5,12 +5,12 @@ namespace HttpServer\Events;
use HttpServer\Abstracts\Callback;
use Snowflake\Core\JSON;
use Snowflake\Event;
use Snowflake\Snowflake;
use Swoole\Server;
use Exception;
use Closure;
use HttpServer\Events\Utility\DataResolve;
/**
* Class OnReceive
@@ -28,35 +28,6 @@ class OnReceive extends Callback
public ?Closure $pack = null;
/**
* @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);
}
/**
* @param Server $server
* @param int $fd
@@ -65,17 +36,18 @@ class OnReceive extends Callback
* @return mixed
* @throws Exception
*/
public function onHandler(\Swoole\Server $server, int $fd,int $reID,string $data)
public function onHandler(\Swoole\Server $server, int $fd, int $reID, string $data)
{
try {
$client = [$fd];
if (empty($data = $this->unpack($data))) {
$data = DataResolve::unpack($this->unpack, null, null, $data);
if (empty($data)) {
throw new Exception('Format error.');
}
$client[] = $this->pack($data);
$client[] = DataResolve::pack($this->pack, $data);
return $server->send(...$client);
} catch (\Throwable $exception) {
$client[] = $this->pack(['message' => $exception->getMessage()]);
$client[] = DataResolve::pack($this->pack, ['message' => $exception->getMessage()]);
return $server->send(...$client);
} finally {
$event = Snowflake::app()->event;