How to manually put data in boost :: asio :: streambuf so that later I can read it using std :: istream?

I am trying to use std :: istream as a data source. I want to place custom binary data in the istream stream buffer so that it can later be retrieved from istream.

I read about boost :: asio :: streambuf and how it is used to do exactly what I want, but using a socket as a data source instead of a buffer in memory that I would like to use.

From what I understand from the documentation , the following steps must be completed:

  • Create boost :: asio :: streambuf
  • Create std :: istream by passing streambuf
  • Call boost :: asio :: streambuf :: prepare to get a list of buffers representing the output sequence.
  • Somehow write in the output sequence.
  • Invoke boost :: asio :: streambuf :: commit to move what I wrote in the output sequence to the input sequence.
  • Reading from std :: istream from step 2 is usually with std :: stream :: read.

I don’t know how to go to step 4, so I don’t know, even if I go in the right direction.

Are the steps shown correct? If so, how to go to step 4?

+4
source share
2 answers

You can easily send any std stream, so you can also use stringstream . You can write binary data to your string stream (it's just an array of bytes, efficiently).

A few samples:

 boost::asio::streambuf request; std::ostream request_stream(&request); request_stream.write(&binarydata_buf, sizeof(binarydata_buf)); // or use stream operators: request_stream << "xxx" << yyy; // Send the request. boost::asio::write(socket, request); 

If you already have a fully populated istream (using std :: cin as dummy in this example):

 boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << std::cin.rdbuf() << std::flush; // Send the request. boost::asio::write(socket, request); 

Istream fill methods are, for example, ostream::write or Boost Serialization binary_archive

There are many ways to throw a cat, of course, so be sure to think about other options before blindly copying it.

See How to send ostream via forced sockets in C ++?

+6
source

Why not just stream data over the socket to your streambuf? If you can associate std :: istream with asio :: streambuf that is listening on a specific socket, just use the same socket with boost :: asio :: write to send it.

There are not many penalties for using actual sockets within a process, and not for simulating it by accessing basic data structures.

0
source

All Articles