以下是一个基本的 C++ WebSocket 连接代码示例,使用了 C++ Boost 库中的 websocket 模块。请注意,这个示例仅仅用于演示如何建立 WebSocket 连接,实际应用需要根据具体场景进行修改和完善。
#include <iostream>
#include <boost/beast.hpp>
#include <boost/asio/ip/tcp.hpp>
// 命名空间
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace asio = boost::asio;
using tcp = boost::asio::ip::tcp;
int main()
{
// 创建 I/O 服务对象
asio::io_context ioc;
// 创建 TCP 协议器
tcp::resolver resolver(ioc);
auto const results = resolver.resolve("echo.websocket.org", "80");
// 创建 WebSocket 对象
websocket::stream<tcp::socket> ws(ioc);
// 设置 SSL/TLS 上下文
ws.set_option(websocket::stream_base::decorator(
[](websocket::response_type& res)
{
res.set(http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro");
}));
// 连接 WebSocket 服务器
asio::connect(ws.next_layer(), results.begin(), results.end());
// 握手
ws.handshake("echo.websocket.org", "/");
// 发送消息
ws.write(asio::buffer(std::string("hello, world")));
// 接收消息
beast::flat_buffer buffer;
ws.read(buffer);
// 输出接收到的消息
std::cout << beast::make_printable(buffer.data()) << std::endl;
// 关闭 WebSocket 连接
ws.close(websocket::close_code::normal);
return 0;
}
需要注意的是,以上代码中使用了 boost 库,需要手动安装并链接到项目中。另外,在实际应用场景中,需要根据具体需要对连接、传输数据和关闭等操作进行处理,以保证 WebSocket 的正常工作。