How to convert boost beast multi_buffer to string?
Asked Answered
A

2

13

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 ?

Aniela answered 18/8, 2017 at 17:18 Comment(0)
G
17

You can use buffers on buffer.data()

std::cout << "Data read:   " << boost::beast::buffers(buffer.data()) << 
std::endl;
Golem answered 22/8, 2017 at 17:47 Comment(3)
Upvoted - This simple technique eluded me for too long. I did: std::ostringstream os; os << boost::beast::buffers(body.data()); std::string s = os.str(); Veolaver
Looks like buffers is deprecated. Use make_printable instead.Abstergent
Yes this is deprecated now. beast::buffers_to_string(buffer.data()) worksKneepad
D
29

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()).

Depreciable answered 29/12, 2018 at 14:27 Comment(0)
G
17

You can use buffers on buffer.data()

std::cout << "Data read:   " << boost::beast::buffers(buffer.data()) << 
std::endl;
Golem answered 22/8, 2017 at 17:47 Comment(3)
Upvoted - This simple technique eluded me for too long. I did: std::ostringstream os; os << boost::beast::buffers(body.data()); std::string s = os.str(); Veolaver
Looks like buffers is deprecated. Use make_printable instead.Abstergent
Yes this is deprecated now. beast::buffers_to_string(buffer.data()) worksKneepad

© 2022 - 2024 — McMap. All rights reserved.