This commit is contained in:
cxh 2026-01-21 14:15:46 +08:00
parent 866499b304
commit b1a906ec18

View File

@ -43,27 +43,26 @@ std::string TunnelClient::handle_local_http(const std::string& method, const std
}
else
{
json err = {{"status", 405}, {"body", "unsupported method"}};
return err.dump();
return json({{"status", 405}, {"body", "unsupported method"}}).dump();
}
if (!res)
{
json err = {{"status", 500}, {"body", "local http error"}};
return err.dump();
return json({{"status", 500}, {"body", "local http error"}}).dump();
}
json resp = {{"status", res->status}, {"body", res->body}};
return resp.dump();
return json({{"status", res->status}, {"body", res->body}}).dump();
}
void TunnelClient::run_loop()
{
ws_client c;
c.clear_access_channels(websocketpp::log::alevel::all);
c.init_asio();
websocketpp::connection_hdl hdl;
// ----------------------- WebSocket 回调 -----------------------
c.set_open_handler(
[&](websocketpp::connection_hdl h)
{
@ -76,27 +75,31 @@ void TunnelClient::run_loop()
c.set_message_handler(
[&](websocketpp::connection_hdl, ws_client::message_ptr msg)
{
// 服务器传来的 HTTP 请求(JSON)
std::string payload = msg->get_payload();
json req = json::parse(payload);
try
{
std::string payload = msg->get_payload();
json req = json::parse(payload);
std::string req_id = req["req_id"];
std::string method = req["method"];
std::string path = req["path"];
std::string body = req.value("body", "");
std::string req_id = req["req_id"];
std::string method = req["method"];
std::string path = req["path"];
std::string body = req.value("body", "");
// 转发给本地 HTTP 服务
std::string result = handle_local_http(method, path, body);
std::string local_result = handle_local_http(method, path, body);
// 包装 response
json resp;
resp["req_id"] = req_id;
resp["resp"] = json::parse(result);
json resp;
resp["req_id"] = req_id;
resp["resp"] = json::parse(local_result);
// 发送回服务器
c.send(hdl, resp.dump(), websocketpp::frame::opcode::text);
c.send(hdl, resp.dump(), websocketpp::frame::opcode::text);
}
catch (...)
{
printf("[Tunnel] JSON or HTTP error\n");
}
});
// ----------------------- 建立连接 -----------------------
websocketpp::lib::error_code ec;
auto conn = c.get_connection(ws_url_, ec);
if (ec)
@ -104,13 +107,16 @@ void TunnelClient::run_loop()
printf("[Tunnel] Connection init failed: %s\n", ec.message().c_str());
return;
}
c.connect(conn);
// ----------------------- 主循环 -----------------------
while (running_)
{
c.run_once();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// 处理一次事件
c.run_one();
// 如果连接停止(断线、错误等)——退出 loop
if (c.stopped()) break;
}
printf("[Tunnel] Loop exit\n");