【问题标题】:Use streambuf as buffer for boost asio read and write使用streambuf作为缓冲区来提升asio读写
【发布时间】:2012-05-26 09:08:25
【问题描述】:

我正在使用此代码阅读

  socket_.async_read_some(boost::asio::buffer(data_, max_length),
        boost::bind(&session::handle_read, this,
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred));

这就是写作

boost::asio::async_write(socket_,
    boost::asio::buffer(data_, bytes_transferred),
    boost::bind(&session::handle_write, this,
    boost::asio::placeholders::error));

其中socket_是socket,max_length是枚举,值为1024,data_是char数组,长度为max_length。

但我想用 streambuf 替换 char 数组缓冲区。我试过了

  boost::asio::streambuf streamBuffer;
  socket_.async_read_some(boost::asio::buffer(streamBuffer),
        boost::bind(&session::handle_read, this,
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred));

但不起作用。我该怎么做?

【问题讨论】:

    标签: c++ boost buffer boost-asio streambuf


    【解决方案1】:

    您需要从streambuf 中获取一个mutable_buffers_type 以用作async_read_some 的第一个参数。

      boost::asio::streambuf streamBuffer;
      boost::asio::streambuf::mutable_buffers_type mutableBuffer =
          streamBuffer.prepare(max_length);
      socket_.async_read_some(boost::asio::buffer(mutableBuffer),
            boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    

    请参阅asio 文档herehere 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-19
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多