C++ Asio 连接到 wss
Posted
技术标签:
【中文标题】C++ Asio 连接到 wss【英文标题】:C++ Asio connect to wss 【发布时间】:2021-03-16 08:15:33 【问题描述】:我正在尝试使用 asio 连接到安全的 websocket。
此示例适用于 IP 地址:
#include <iostream>
#include <asio.hpp>
int main()
asio::error_code ec;
asio::io_context context;
asio::io_context::work idleWork(context);
asio::ip::tcp::endpoint endpoint(asio::ip::make_address("51.38.81.49", ec), 80);
asio::ip::tcp::socket socket(context);
socket.connect(endpoint, ec);
if (!ec)
std::cout << "Connected!" << std::endl;
else
std::cout << "Failed to connect to address: \n" << ec.message() << std::endl;
return 0;
但我将如何更改它以便连接到“wss://api2.example.com”?
编辑:
感谢您的回答 karastojko - 这似乎让我有所了解。我想知道我是否真的连接到服务器,所以我用你的输入更新了我的示例,添加了一个我知道会回答并创建读写的工作 WSS。
#include <asio.hpp>
#include <asio/ts/buffer.hpp>
std::vector<char> vBuffer(1 * 1024);
// This should output the received data
void GrabSomeData(asio::ip::tcp::socket& socket)
socket.async_read_some(asio::buffer(vBuffer.data(), vBuffer.size()),
[&](std::error_code ec, std::size_t lenght)
if (!ec)
std::cout << "\n\nRead " << lenght << " bytes\n\n";
for (int i = 0; i < lenght; i++)
std::cout << vBuffer[i];
GrabSomeData(socket);
);
int main()
asio::error_code ec;
asio::io_context context;
asio::io_context::work idleWork(context);
std::thread thrContext = std::thread([&]() context.run(); );
// I hope this is what you meant
asio::ip::tcp::resolver res(context);
asio::ip::tcp::socket socket(context);
asio::connect(socket, res.resolve("echo.websocket.org", std::to_string(443)));
// Check the socket is open
if (socket.is_open())
// Start to output incoming data
GrabSomeData(socket);
// Send data to the websocket, which should be sent back
std::string sRequest = "Echo";
socket.write_some(asio::buffer(sRequest.data(), sRequest.size()), ec);
// Wait some time, so the data is received
using namespace std::chrono_literals;
std::this_thread::sleep_for(20000ms);
context.stop();
if (thrContext.joinable()) thrContext.join();
return 0;
【问题讨论】:
【参考方案1】:为此使用resolver 类:
tcp::resolver res(context);
asio::ip::tcp::socket socket(context);
boost::asio::connect(socket, res.resolve("api2.example.com", 80));
【讨论】:
以上是关于C++ Asio 连接到 wss的主要内容,如果未能解决你的问题,请参考以下文章
无法连接到 wss://(连接建立错误:net::ERR_CONNECTION_CLOSED)
WebSocket 连接到“wss://argus.chi.shopify.io”失败:WebSocket 在连接建立之前关闭
WebSocket 连接到“wss://test.example.com:8090/”失败:WebSocket 打开握手超时
尝试使用boost :: asio连接到SOCKS 5服务器,但我的连接请求结果不正确
WebSocket 连接到“wss://mydomain.com/one/of/app/graphql”失败 - NestJS GraphQL、docker、nginx