xy 3 周之前
父节点
当前提交
5714e0cd50
共有 2 个文件被更改,包括 35 次插入5 次删除
  1. 25 2
      src/GameClient.php
  2. 10 3
      src/main.php

+ 25 - 2
src/GameClient.php

@@ -18,7 +18,8 @@ class GameClient {
     private ?WebSocketClient $client = null;
     private ?string $userId = null;
     private ?string $nikeName = null;
-
+    private ?int $listenerPid = null;
+    private bool $isRunning = false;
     public function start() {
         // $this->login();
     }
@@ -127,8 +128,30 @@ class GameClient {
         if (!$this->client) {
             throw new Exception("WebSocket连接未建立");
         }
+        
+        if ($this->listenerPid !== null) {
+            return; // 已经启动监听
+        }
+
         echo "开始监听WebSocket消息...\n";
-        $this->client->startListening();
+        
+        $pid = pcntl_fork();
+        if ($pid == -1) {
+            throw new Exception("无法创建子进程");
+        } elseif ($pid == 0) {
+            // 子进程:持续监听WebSocket
+            $this->isRunning = true;
+            $this->client->startListening();
+            exit(0);
+        } else {
+            // 父进程记录子进程ID
+            $this->listenerPid = $pid;
+            $this->isRunning = true;
+        }
+    }
+
+    public function isRunning(): bool {
+        return $this->isRunning;
     }
     private function enterHall($userId) {
         if (!$this->client) {

+ 10 - 3
src/main.php

@@ -15,11 +15,18 @@ class ProgramMain {
     public static function runInteractiveCli(): void {
         $client = self::getClient();
         
+        // 设置信号处理
+        pcntl_async_signals(true);
+        pcntl_signal(SIGINT, function() use ($client) {
+            $client->close();
+            exit(0);
+        });
+
         echo "游戏客户端交互模式(输入命令执行,如 login, outGame, exit)\n";
         
         while (true) {
-            $input = readline("> ");  // 等待用户输入
-            $args = explode(' ', $input);  // 拆解命令和参数
+            $input = readline("> ");
+            $args = explode(' ', $input);
             
             switch ($args[0]) {
                 case 'login':
@@ -33,7 +40,7 @@ class ProgramMain {
                     $client->outGame();
                     break;
                 case 'exit':
-                    $client->close();  // 关闭 WebSocket 连接
+                    $client->close();
                     exit(0);
                 default:
                     echo "未知命令。可用命令: login, outGame, exit\n";