Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send ostream via boost sockets in C++?

I am facing some issues with my inter-process communication using protobuf. Protobuf allows a set of serialization formats:

SerializeToArray(void * data, int size) : bool
SerializeToCodedStream(google::protobuf::io::CodeOutputStream * output) : bool
SerializeToFileDescriptor(int file_descriptor) : bool
SerializeToOstream(ostream * output)

My problem is, I have no clue how to use it with the boost asio sockets I am using, as I implemented them to send strings:

boost::asio::write(socket, boost::asio::buffer(message),
            boost::asio::transfer_all(), ignored_error);

But I would like to send the ostream.

like image 321
Konrad Reiche Avatar asked Dec 21 '22 15:12

Konrad Reiche


1 Answers

Boost's asio library integrates with std iostream on the level of streambuffers

So write a request

boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET " << argv[2] << " HTTP/1.0\r\n";
request_stream << "Host: " << argv[1] << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";

// Send the request.
boost::asio::write(socket, request);

Read a response:

boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");

// Check that response is OK.
std::istream response_stream(&response);

Copy a stream:

boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << std::cin.rdbuf() << std::flush;

// Send the request.
boost::asio::write(socket, request);
like image 157
sehe Avatar answered Jan 02 '23 11:01

sehe