C++ Boost asio connect and stream

Viewed 540

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());
    
}
1 Answers

websocket::stream class, and perform the handshake, writing and reading data using this class?

That's because websocket::stream implements the websocket protocol over any AsyncStream. That makes it so you can plug in a pipe, UNIX domain socket, TCP stream or SSL stream, and the protocol will still work on all of those.

Shouldn't there be any methods within socket that would do this?

Oh sure, but then you break out of the abstraction layer of the WebSocket protocol and you would likely break it.

It's a bit like saying "But can't I just go and write by word docx file in a hex editor". Sure you can, but you'll not be happier and probably lose work often.

Related