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-04 01:05:33 +08:00
|
|
|
use HttpServer\Abstracts\Callback;
|
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;
|
|
|
|
|
use Closure;
|
2020-11-04 19:28:40 +08:00
|
|
|
use HttpServer\Events\Utility\DataResolve;
|
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
|
|
|
|
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
|
|
|
|
|
|
|
|
|
2020-08-31 01:27:08 +08:00
|
|
|
/**
|
|
|
|
|
* @param Server $server
|
|
|
|
|
* @param int $fd
|
2020-11-01 04:37:39 +08:00
|
|
|
* @param int $reID
|
2020-08-31 01:27:08 +08:00
|
|
|
* @param string $data
|
|
|
|
|
* @return mixed
|
|
|
|
|
* @throws Exception
|
|
|
|
|
*/
|
2020-12-17 14:09:14 +08:00
|
|
|
public function onHandler(\Swoole\Server $server, int $fd, int $reID, string $data): mixed
|
2020-08-31 01:27:08 +08:00
|
|
|
{
|
|
|
|
|
try {
|
2020-11-14 02:00:09 +08:00
|
|
|
$client = $server->getClientInfo($fd, $reID);
|
|
|
|
|
|
|
|
|
|
$data = DataResolve::unpack($this->unpack, $client['remote_ip'], $client['remote_port'], $data);
|
2020-11-04 19:28:40 +08:00
|
|
|
if (empty($data)) {
|
2020-08-31 01:27:08 +08:00
|
|
|
throw new Exception('Format error.');
|
|
|
|
|
}
|
2020-11-05 18:35:38 +08:00
|
|
|
return $server->send($fd, DataResolve::pack($this->pack, $data));
|
2020-08-31 01:27:08 +08:00
|
|
|
} catch (\Throwable $exception) {
|
2020-11-05 18:35:38 +08:00
|
|
|
$response['message'] = $exception->getMessage();
|
|
|
|
|
$response['state'] = 500;
|
|
|
|
|
$response = DataResolve::pack($this->pack, $response);
|
|
|
|
|
return $server->send($fd, $response);
|
2020-08-31 01:27:08 +08:00
|
|
|
} 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);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|