Boost-Beast 异步网络套接字服务器-客户端异步读写不在控制台上写入输出

Boost-Beast async web socket Server-Client async read-write not writing output on console

我正在尝试异步的 Boost Beast 示例 web socket server - client

我是运行服务器和客户端如下,

server.exe 127.0.0.1 4242 1

client.exe 127.0.0.1 4242 "Hello"

如果一切正常,我相信它应该在服务器命令提示符

上打印 "Hello"

下面是代码

void
        on_read(
        beast::error_code ec,
        std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        // This indicates that the session was closed
        if (ec == websocket::error::closed)
            return;

        if (ec)
            fail(ec, "read");

        // Echo the message
        ws_.text(ws_.got_text());

        std::cout << "writing received value " << std::endl;
        ws_.async_write(
            buffer_.data(),
            beast::bind_front_handler(
            &session::on_write,
            shared_from_this()));

        std::cout << buffer_.data().data()<< std::endl;
    }

ws_.write() 没有在控制台上写任何东西,但是 buffer_data.data() 呈现 00000163E044EE80

我如何确保它工作正常?如何从套接字缓冲区中检索字符串值?

发送消息行打印内容要放在async_write之前:

    std::cout << buffer_.data().data()<< std::endl;

    ws_.async_write(
        buffer_.data(),
        beast::bind_front_handler(
        &session::on_write,
        shared_from_this()));

为什么?

BOOST-ASIO/BEAST 中以 async_ 开头的所有函数总是立即 return。它们启动一些任务,这些任务在后台 asio 核心中执行,当它们准备就绪时,将调用处理程序。

查看on_write处理程序:

void
    on_write(
        beast::error_code ec,
        std::size_t bytes_transferred)
{
    boost::ignore_unused(bytes_transferred);

    if (ec)
        return fail(ec, "write");

    // Clear the buffer
    buffer_.consume(buffer_.size());  /// <---

consumebuffer_.

的开头删除长度为 buffer_size 的字节块

您的问题是缓冲区可能已被清除然后打印:

thread 1             thread 2
------------------------------   | steps
  async_write      |             | [1]
                   |  consume    | [2]
  cout << buffer_  |             | [3]
                                 | 

除了在使用缓冲区之前使用缓冲区外,为了转换缓冲区,我还必须编写 to_string_ 函数,该函数采用平面缓冲区和 returns 字符串

std::string to_string_(beast::flat_buffer const& buffer)
{
    return std::string(boost::asio::buffer_cast<char const*>(
        beast::buffers_front(buffer.data())),
        boost::asio::buffer_size(buffer.data()));
};

发现 beast::buffers_to_string(buffer_.data()) 也可以轻松完成此操作。

参考:trying-to-understand-the-boostbeast-multibuffer