Boost-Beast异步Web套接字Server-Client异步读写未在控制台上写入输出

时间:2019-07-19 14:27:17

标签: c++ boost boost-asio boost-beast

我正在尝试异步web socket server-client

的Boost Beast示例

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

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

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

2 个答案:

答案 0 :(得分:1)

已发送消息的行打印内容应放在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_开头的函数始终会立即返回。他们启动一些任务,这些任务在后台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_size的开头删除长度为buffer_的字节块。

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

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

答案 1 :(得分:1)

除了使用缓冲区消耗的缓冲区来转换缓冲区外,我还必须编写to_string_函数,该函数采用平坦缓冲区并返回字符串

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