4
votes

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.

2
You could use an ostringstream, serialize to it with protobuf, convert it's string-value .str() into a boost buffer, and send that. You don't plan to have full stream semantics on message exchanging sockets automagically, do you?Jonas Bötel

2 Answers

11
votes

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

What about using ostringstream?

ostringstream oss;

oss << "hello world";

std::string str(oss.str());