Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert boost beast multi_buffer to string?

I copy websocket example from boost::beast website and run it Websocket session work fine but I don't know how to convert received multi_buffer to string.

below code is websocket session handler.

void
do_session(tcp::socket &socket) {
    try {
        // Construct the stream by moving in the socket
        websocket::stream <tcp::socket> ws{std::move(socket)};

        // Accept the websocket handshake
        ws.accept();

        while (true) {
            // This buffer will hold the incoming message
            boost::beast::multi_buffer buffer;

            // Read a message
            boost::beast::error_code ec;
            ws.read(buffer, ec);

            if (ec == websocket::error::closed) {
                break;
            }

            // Echo the message back
            ws.text(ws.got_text());
            ws.write(buffer);
        }

        cout << "Close" << endl;
    }
    catch (boost::system::system_error const &se) {
        // This indicates that the session was closed
        if (se.code() != websocket::error::closed)
            std::cerr << "Error: " << se.code().message() << std::endl;
    }
    catch (std::exception const &e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}

Is there way to convert buffer to string ?

like image 444
MohsenTi Avatar asked Aug 18 '17 17:08

MohsenTi


2 Answers

Since original question was about converting to string directly, without using streams, I decided to add my answer.

You can use beast::buffers_to_string(buffer.data()).

like image 107
John Tracid Avatar answered Nov 07 '22 08:11

John Tracid


You can use buffers on buffer.data()

std::cout << "Data read:   " << boost::beast::buffers(buffer.data()) << 
std::endl;
like image 25
Fabio Carvalho Avatar answered Nov 07 '22 09:11

Fabio Carvalho