使用streambuf作为缓冲区来进行boost asio读写

时间:2012-05-26 09:08:25

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

我正在使用此代码进行阅读

  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));

但是没有用。我该怎么办?

1 个答案:

答案 0 :(得分:16)

您需要从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