diff --git a/HttpServer/Server.php b/HttpServer/Server.php index 8eed443e..88b86c46 100644 --- a/HttpServer/Server.php +++ b/HttpServer/Server.php @@ -175,13 +175,7 @@ class Server extends HttpService return false; } foreach ($port as $value) { - if (Snowflake::getPlatform()->isLinux()) { - exec('netstat -tunlp | grep ' . $value['port'], $output); - } else { - exec('lsof -i :' . $value['port'] . ' | grep -i "LISTEN"', $output); - } - if (!empty($output)) { - unset($output); + if ($this->checkPort($value['port'])) { return true; } } @@ -189,6 +183,22 @@ class Server extends HttpService } + /** + * @param $port + * @return bool + * @throws Exception + */ + private function checkPort($port): bool + { + if (Snowflake::getPlatform()->isLinux()) { + exec('netstat -tunlp | grep ' . $port, $output); + } else { + exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output); + } + return !empty($output); + } + + /** * @return void * @@ -312,7 +322,7 @@ class Server extends HttpService */ private function dispatchCreate($config, $settings): \Swoole\Server|Packet|Receive|Http|Websocket|null { - if ($this->isUse($config['port'])) { + if (Snowflake::port_already($config['port'])) { return $this->error_stop($config['host'], $config['port']); } if (!($this->baseServer instanceof \Swoole\Server)) { diff --git a/Rpc/Service.php b/Rpc/Service.php index ae85ce22..af902a80 100644 --- a/Rpc/Service.php +++ b/Rpc/Service.php @@ -57,6 +57,12 @@ class Service extends Component private function addService($router, $server, $service) { $mode = $service['mode'] ?? SWOOLE_SOCK_TCP6; + + if (Snowflake::port_already($service['port'])) { + throw new Exception(sprintf('Port %s::%d is already.', $service['host'], $service['port'])); + } + $this->debug(sprintf('Port %s::%d is already.', $service['host'], $service['port'])); + $rpcServer = $server->addlistener($service['host'], $service['port'], $mode); $rpcServer->set([ 'open_tcp_keepalive' => true, diff --git a/System/Snowflake.php b/System/Snowflake.php index 5fb60ed7..5ed8529d 100644 --- a/System/Snowflake.php +++ b/System/Snowflake.php @@ -83,6 +83,25 @@ class Snowflake } + /** + * @param $port + * @return bool|array + * @throws Exception + */ + public static function port_already($port): bool + { + if (empty($port)) { + return false; + } + if (Snowflake::getPlatform()->isLinux()) { + exec('netstat -tunlp | grep ' . $port, $output); + } else { + exec('lsof -i :' . $port . ' | grep -i "LISTEN"', $output); + } + return !empty($output); + } + + /** * @param $className * @param array $construct