abyss.7
abyss.7

Reputation: 14462

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

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

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

Upvotes: 8

Views: 2965

Answers (2)

Rawler
Rawler

Reputation: 1620

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?

Upvotes: 9

Nim
Nim

Reputation: 33655

The asio::buffer free function can accept a collection of buffers (for example this), the resulting buffer is not a copy of the buffers, but a sequence - which will be sent.

Upvotes: 1

Related Questions