You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Boost C++连接WebSocket服务端时如何正确指定路径

问题根源

你出现连接失败是两个错误操作导致的:

  • 初始代码中WebSocket握手请求的路径参数填的是根路径/,和你服务端实际暴露的WebSocket路径/webstream/wsocket不匹配
  • 后续修改时错误地把路径拼接到了主机名参数里,主机名仅用于DNS解析和TCP连接,不能携带路径信息,会直接导致域名解析失败

正确修改方案

你只需要调整两处配置即可:

  1. 主机名保持为纯域名/IP localhost,不要拼接任何路径
  2. 将websocket::stream::handshake方法的第二个参数改为你服务端的实际WebSocket路径/webstream/wsocket

修正后的核心代码如下:

tcp::resolver resolver{ioc};
_pws = new websocket::stream<tcp::socket>(ioc);

// 主机名仅填域名/IP,不要带路径
_host = "localhost";
_port = 80;

auto const results = resolver.resolve(_host, std::to_string(_port));
if(results.size() == 0)
{
    std::cout<<"failed to resolve host"<<std::endl;
    delete _pws;
    _pws = nullptr;
    return;
}

net::connect(_pws->next_layer(), results.begin(), results.end());

_pws->set_option(websocket::stream_base::decorator(
    [](websocket::request_type& req)
    {
        req.set(http::field::user_agent,
            std::string(BOOST_BEAST_VERSION_STRING) +
                " websocket-client-coro");
    }));
// 握手第二个参数填完整的WebSocket服务路径
_pws->handshake(_host, "/webstream/wsocket");

附加排查建议

如果修改后仍然连接失败,可以增加错误码捕获逻辑定位具体问题:

boost::system::error_code ec;
_pws->handshake(_host, "/webstream/wsocket", ec);
if (ec) {
    std::cout << "websocket handshake failed: " << ec.message() << std::endl;
    // 错误处理逻辑
}

内容的提问来源于stack exchange,提问作者Dilip ND

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 11:15:05