I'm new to Websockets, and I'm confused as to the need for the boost::beast::websocket::stream class. I'm attaching an example code below. From what I gather, socket.connect would talk to the I/O object and sort of establish the connection with the server. Why then would I need to pass this to a websocket::stream class, and perform the handshake, writing and reading data using this class? Shouldn't there be any methods within socket that would do this? Could someone help elaborate? Thank you
#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());
}