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) { var_dump($message); // 向所有连接的客户端发送消息 foreach ($this->clients as $client) { var_dump($client); var_dump($message); $client->send($message); } } }