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

+ 82 - 0
app/Console/Commands/WebSocketServer.php

@@ -0,0 +1,82 @@
+<?php
+
+namespace App\Console\Commands;
+
+use Ratchet\MessageComponentInterface;
+use Ratchet\ConnectionInterface;
+use Ratchet\Server\IoServer;
+use Ratchet\Http\HttpServer;
+use Ratchet\WebSocket\WsServer;
+use Illuminate\Console\Command;
+
+class WebSocketServer extends Command
+{
+    protected $signature = 'websocket:start';
+    protected $clients;
+
+    public function __construct()
+    {
+        parent::__construct();
+        $this->clients = new \SplObjectStorage;
+    }
+
+    public function handle()
+    {
+        $this->info('WebSocket server starting on ws://121.37.173.82:6002');
+        $server = IoServer::factory(
+            new HttpServer(
+                new WsServer(
+                    new class($this) implements MessageComponentInterface {
+                        private $server;
+
+                        public function __construct($server)
+                        {
+                            $this->server = $server;
+                        }
+
+                        public function onOpen(ConnectionInterface $conn)
+                        {
+                            $this->server->clients->attach($conn);
+                            echo "New connection! ({$conn->resourceId})\n";
+                        }
+
+                        public function onMessage(ConnectionInterface $from, $msg)
+                        {
+                            echo "Message from {$from->resourceId}: $msg\n";
+                            foreach ($this->server->clients as $client) {
+                                if ($from !== $client) {
+                                    $client->send($msg);
+                                }
+                            }
+                        }
+
+                        public function onClose(ConnectionInterface $conn)
+                        {
+                            $this->server->clients->detach($conn);
+                            echo "Connection {$conn->resourceId} has disconnected\n";
+                        }
+
+                        public function onError(ConnectionInterface $conn, \Exception $e)
+                        {
+                            echo "Error: {$e->getMessage()}\n";
+                            $conn->close();
+                        }
+                    }
+                )
+            ),
+            6002
+        );
+
+        $server->run();
+    }
+
+    public function pushMessageToClients($message)
+    {
+        // 向所有连接的客户端发送消息
+        foreach ($this->clients as $client) {
+            $client->send($message);
+        }
+    }
+}
+
+