TCP

EasySwoole创建TCP服务器,有两种以下方式:

主服务

修改配置文件MAIN_SERVER.SERVER_TYPEEASYSWOOLE_SERVER

EasySwooleEventmainServerCreate事件进行回调注册:

  1. public static function mainServerCreate(\EasySwoole\EasySwoole\Swoole\EventRegister $register)
  2. {
  3. $register->add($register::onConnect, function (\Swoole\Server $server, int $fd, int $reactor_id) {
  4. echo "fd {$fd} connected";
  5. });
  6. $register->add($register::onReceive, function (\Swoole\Server $server, int $fd, int $reactor_id, string $data) {
  7. echo "fd:{$fd} send:{$data}\n";
  8. });
  9. $register->add($register::onClose, function (\Swoole\Server $server, int $fd, int $reactor_id) {
  10. echo "fd {$fd} closed";
  11. });
  12. }

子服务

顾名思义:另开一个端口进行tcp监听。

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. 'open_length_check' => false,
  8. ]);
  9. $subPort->on($register::onConnect, function (\Swoole\Server $server, int $fd, int $reactor_id) {
  10. echo "fd {$fd} connected";
  11. });
  12. $subPort->on($register::onReceive, function (\Swoole\Server $server, int $fd, int $reactor_id, string $data) {
  13. echo "fd:{$fd} send:{$data}\n";
  14. });
  15. $subPort->on($register::onClose, function (\Swoole\Server $server, int $fd, int $reactor_id) {
  16. echo "fd {$fd} closed";
  17. });
  18. }