4

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.

Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143
  • 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 Apr 15 '11 at 10:31

2 Answers2

11

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);
sehe
  • 374,641
  • 47
  • 450
  • 633
0

What about using ostringstream?

ostringstream oss;

oss << "hello world";

std::string str(oss.str());
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415