【发布时间】:2021-09-17 15:01:28
【问题描述】:
我是 Websockets 的新手,我对 boost::beast::websocket::stream 类的需求感到困惑。我在下面附上了一个示例代码。据我所知,socket.connect 将与 I/O 对象对话并建立与服务器的连接。那么为什么我需要将它传递给 websocket::stream 类,并使用该类执行握手、写入和读取数据?套接字中不应该有任何方法可以做到这一点吗?有人可以帮忙详细说明吗?谢谢
#include <boost/beast.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
#include <iomanip>
#include <iostream>
#include <thread>
using tcp = boost::asio::ip::tcp;
int main()
{
std::string url = "ltnm.learncppthroughprojects.com";
std::string port = "80";
// Create a I/O context
boost::asio::io_context ioc {};
// Create an I/O object, that takes in the io context as an intermediary to talk with you
tcp::socket socket (ioc);
// Resolve address to ip
boost::system::error_code ec {};
tcp::resolver resolver {ioc};
auto resolverIt {resolver.resolve(url, port, ec)};
// Talk to the socket using I/O context
socket.connect(*resolverIt);
// Now that talking to the socket is succcessful,
// we tie the socket object to a websocket stream
boost::beast::websocket::stream<boost::beast::tcp_stream> ws(std::move(socket));
// Now, perform a websocket handshake
ws.handshake(url,"/echo",ec);
// Now the socket is connected to the server, write data to it
boost::asio::const_buffer data("toioest",7);
ws.write(data);
boost::beast::flat_buffer response;
ws.read(response);
std::cout<<boost::beast::make_printable(response.data());
}
【问题讨论】:
标签: c++ websocket boost-asio boost-beast