login(); } private function login() { $loginReq = new ReqLogin(); $loginReq->setAccount("xy1"); $loginReq->setPassword('123'); $binaryData = $loginReq->serializeToString(); if (empty($binaryData)) { throw new Exception("序列化失败:返回空数据"); } $options = [ 'http' => [ 'method' => 'POST', 'header' => implode("\r\n", [ 'Content-Type: application/x-protobuf', 'Accept: */*', 'Accept-Language: zh-CN,zh;q=0.9', 'Connection: keep-alive', 'Referer: http://localhost:7456/' ]), 'content' => $binaryData, 'timeout' => 10, 'ignore_errors' => false ] ]; try { $url = 'http://120.76.130.29:8080/ReqLogin'; $context = stream_context_create($options); $response = file_get_contents($url, false, $context); if ($response === false) { throw new Exception("请求失败: " . error_get_last()['message']); } if (strpos($response, '404 page not found') !== false) { throw new Exception("API端点不存在(404),请检查URL: " . $url); } $userResponse = new ResLogin(); $userResponse->mergeFromString($response); if ($userResponse->getErrMsg() !== null) { throw new Exception("登录失败: " . $userResponse->getErrMsg()->getMessage()); } echo "登录成功!\n"; echo "用户ID: " . $userResponse->getUserId() . "\n"; echo "昵称: " . $userResponse->getNikeName() . "\n"; $this->userId = $userResponse->getUserId(); $this->nikeName = $userResponse->getNikeName(); $this->initWebSocketConnection(); echo "是否成功获取信息: " .$userResponse->hasUserInfo() . "\n"; if ($userResponse->hasUserInfo()) { $this->enterHall($userResponse->getUserInfo()->getUserId()); } } catch (Exception $e) { echo $e->getMessage() . "\n"; exit(1); } } private function initWebSocketConnection() { $this->client = new WebSocketClient('ws://localhost:3653'); $this->client->on(MsgID::RESENTERHALL, function($binaryData) { $response = new ResEnterHall(); $response->mergeFromString($binaryData); echo "成功进入大厅!\n"; echo "大厅玩家数: " . $response->getSuccess() . "\n"; }); $this->client->startListening(); } private function enterHall($userId) { if (!$this->client) { throw new Exception("WebSocket连接未建立"); } $enterHall = new EnterHall(); $enterHall->setUserId($userId); $binaryData = $enterHall->serializeToString(); $this->client->sendBinary(MsgID::ENTERHALL, $binaryData); echo "已发送进入大厅请求\n"; } } // 启动客户端 $gameClient = new GameClient(); $gameClient->start();