Socket-Controller

创建

继承EasySwoole\Socket\AbstractInterface\Controller

  1. class Test extends \EasySwoole\Socket\AbstractInterface\Controller
  2. {
  3. }

自定义解析器

  1. class TestParser implements \EasySwoole\Socket\AbstractInterface\ParserInterface
  2. {
  3. public function decode($raw,$client) : ?\EasySwoole\Socket\Bean\Caller
  4. {
  5. }
  6. public function encode(\EasySwoole\Socket\Bean\Response $response,$client) : ?string
  7. {
  8. }
  9. }

调度器注册

子服务举例

EasySwooleEventmainServerCreate事件进行回调注册:

  1. public static function mainServerCreate(\EasySwoole\EasySwoole\Swoole\EventRegister $register)
  2. {
  3. $server = \EasySwoole\EasySwoole\ServerManager::getInstance()->getSwooleServer();
  4. $subPort = $server->addlistener('0.0.0.0', 9502, SWOOLE_TCP);
  5. $subPort->set(
  6. // swoole 相关配置
  7. );
  8. $socketConfig = new \EasySwoole\Socket\Config();
  9. $socketConfig->setType($socketConfig::TCP);
  10. $socketConfig->setParser(new TestParser());
  11. //设置解析异常时的回调,默认将抛出异常到服务器
  12. $socketConfig->setOnExceptionHandler(function ($server, $throwable, $raw, $client, \EasySwoole\Socket\Bean\Response $response) {
  13. $response->setMessage("服务器异常(客户端fd:{$client->getFd()})");
  14. $response->setStatus($response::STATUS_RESPONSE_AND_CLOSE); // 发送完主动关闭该连接
  15. });
  16. $dispatch = new \EasySwoole\Socket\Dispatcher($socketConfig);
  17. $subPort->on($register::onConnect, function (\Swoole\Server $server, int $fd, int $reactor_id) {
  18. echo "fd {$fd} connected";
  19. });
  20. $subPort->on($register::onReceive, function (\Swoole\Server $server, int $fd, int $reactor_id, string $data) use ($dispatch) {
  21. $dispatch->dispatch($server, $data, $fd, $reactor_id);
  22. });
  23. $subPort->on($register::onClose, function (\Swoole\Server $server, int $fd, int $reactor_id) {
  24. echo "fd {$fd} closed";
  25. });
  26. }