gogs 9 місяців тому
батько
коміт
5df1877edd
1 змінених файлів з 13 додано та 9 видалено
  1. 13 9
      app/Console/Commands/WebSocketServer.php

+ 13 - 9
app/Console/Commands/WebSocketServer.php

@@ -13,6 +13,7 @@ class WebSocketServer extends Command
 {
     protected $signature = 'websocket:start';
     public $clients;
+    protected $serverInstance;
 
     public function __construct()
     {
@@ -23,7 +24,9 @@ class WebSocketServer extends Command
     public function handle()
     {
         $this->info('WebSocket server starting on ws://121.37.173.82:6002');
-        $server = IoServer::factory(
+
+        // 创建WebSocket服务器实例
+        $this->serverInstance = IoServer::factory(
             new HttpServer(
                 new WsServer(
                     new class($this) implements MessageComponentInterface {
@@ -38,7 +41,6 @@ class WebSocketServer extends Command
                         {
                             $this->server->clients->attach($conn);
                             echo "New connection! ({$conn->resourceId})\n";
-
                         }
 
                         public function onMessage(ConnectionInterface $from, $msg)
@@ -68,19 +70,21 @@ class WebSocketServer extends Command
             6002
         );
 
-        $server->run();
+        // 启动WebSocket服务器
+        $this->serverInstance->run();
     }
 
+    // 将WebSocket服务器的实例暴露给外部
     public function pushMessageToClients($message)
     {
-        var_dump($message);
-        // 向所有连接的客户端发送消息
-        foreach ($this->clients as $client) {
-            var_dump($client);
-            var_dump($message);
-            $client->send($message);
+        if ($this->serverInstance) {
+            // 向所有连接的客户端发送消息
+            foreach ($this->clients as $client) {
+                $client->send($message);
+            }
         }
     }
 }
 
 
+