clients = new \SplObjectStorage(); } // 当新客户端连接时触发 public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "新客户端连接: {$conn->resourceId}\n"; } // 收到客户端消息时触发 public function onMessage(ConnectionInterface $from, $msg) { echo "收到消息: $msg\n"; //将消息发送给所有用户 foreach ($this->clients as $client) { $client->send($msg); } // 原样回复客户端 //$from->send("服务器回复: $msg"); // 收到 "exit" 时关闭连接 if ($msg === 'exit') { $from->close(); } } // 当客户端断开时触发 public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "客户端断开: {$conn->resourceId}\n"; } // 错误处理 public function onError(ConnectionInterface $conn, \Exception $e) { echo "错误: {$e->getMessage()}\n"; $conn->close(); } //公共方法 public function curlPost($url,$data){ // 初始化 cURL $ch = curl_init(); // 设置 cURL 选项 curl_setopt($ch, CURLOPT_URL, $url); // 设置 URL curl_setopt($ch, CURLOPT_POST, true); // 设置为 POST 请求 curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 设置 POST 数据 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将返回结果保存到变量而不是直接输出 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 执行请求并获取响应 $response = curl_exec($ch); // 检查是否有错误发生 if(curl_errno($ch)){ echo 'cURL 错误: ' . curl_error($ch); } // 关闭 cURL 资源并释放内存 curl_close($ch); // 处理响应数据(如果需要) return $response; } //将对象转为数组 public function stdClassObjToArray($array) { if(is_object($array)) { $array = (array)$array; } if(is_array($array)) { foreach($array as $key=>$value) { $array[$key] = $this->stdClassObjToArray($value); } } return $array; } } // 创建 WebSocket 服务器(监听 8033 端口) $server = IoServer::factory( new HttpServer(new WsServer(new MyWebSocketHandler())), 8023, '0.0.0.0' // 明确指定监听所有接口 ); echo "WebSocket 服务器已启动 (端口 8023)...\n"; $server->run();