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 ?
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())
.
You can use buffers on buffer.data()
std::cout << "Data read: " << boost::beast::buffers(buffer.data()) <<
std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With