简体   繁体   中英

Use streambuf as buffer for boost asio read and write

I'm using this code for reading

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

and this for writing

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

where socket_ is socket, max_length is enum with value 1024 and data_ is char array with length of max_length.

But I want to replace char array buffer with streambuf. I've tried

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

But isn't working. How can I do it ?

You need to get a mutable_buffers_type from the streambuf to use as your first parameter to 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));

See the asio documentation here and here for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM