Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two boost::asio::streambuf's?

Tags:

c++

boost-asio

I use boost::asio as a network framework. As a read/write medium it uses boost::asio::streambuf. I want to:

  • read some message in one buffer
  • append second buffer at the beginning of the first one
  • send new composite message

What are the possible efficient (zero-copy) options to do this?

like image 916
abyss.7 Avatar asked Feb 27 '12 10:02

abyss.7


1 Answers

The principle is called scatter/gather IO. Basically a way of transmitting multiple buffers at once (in order), without expensive memory-copying. It is well supported under boost::asio with the very flexible and powerful, (but also difficult to grasp) buffers-concept, and buffer-sequence concept.

A simple (untested, but I believe correct) example to get you started, would be:

std::vector<boost::asio::streambuf::const_buffers_type> buffers;
buffers.push_back( my_first_streambuf.data() );
buffers.push_back( my_second_streambuf.data() );

std::size_t length = boost::asio::write( mySocket, buffers );

Of course, one simple option would be to just read both messages into the streambuf and simply sending the entire streambuf, but from your question I'm guessing it's not an option for some reason?

like image 169
Rawler Avatar answered Sep 22 '22 12:09

Rawler