如何将boost beast multi_buffer转换为字符串?

Moh*_*nTi 6 c++ boost boost-beast

我从boost :: beast网站复制websocket示例并运行它的Websocket会话工作正常,但我不知道如何将收到的multi_buffer转换为字符串.

下面的代码是websocket会话处理程序.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法将缓冲区转换为字符串?

小智 12

您可以使用缓冲区buffer.data()

std::cout << "Data read:   " << boost::beast::buffers(buffer.data()) << 
std::endl;
Run Code Online (Sandbox Code Playgroud)

  • 是的,现在已弃用。`beast::buffers_to_string(buffer.data())` 有效 (7认同)
  • 似乎不建议使用“ buffers”。使用`make_printable`代替。 (2认同)

Joh*_*cid 6

由于最初的问题是关于不使用流而直接转换为字符串的问题,因此我决定添加我的答案。

您可以使用beast::buffers_to_string(buffer.data())