我在使用protobuf进行进程间通信时遇到了一些问题。Protobuf允许一组序列化格式:
SerializeToArray(void * data, int size) : bool
SerializeToCodedStream(google::protobuf::io::CodeOutputStream * output) : bool
SerializeToFileDescriptor(int file_descriptor) : bool
SerializeToOstream(ostream * output)
我的问题是,我不知道如何使用它与我正在使用的boost asio套接字,因为我实现它们来发送字符串:
boost::asio::write(socket, boost::asio::buffer(message),
boost::asio::transfer_all(), ignored_error);
但是我想发送ostream.
Boost的asio库在streambuffers级别上与std iostream集成
写一个请求
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET " << argv[2] << " HTTP/1.0rn";
request_stream << "Host: " << argv[1] << "rn";
request_stream << "Accept: */*rn";
request_stream << "Connection: closernrn";
// Send the request.
boost::asio::write(socket, request);
读取响应:
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "rn");
// Check that response is OK.
std::istream response_stream(&response);
复制流:
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << std::cin.rdbuf() << std::flush;
// Send the request.
boost::asio::write(socket, request);
使用ostringstream怎么样?
ostringstream oss;
oss << "hello world";
std::string str(oss.str());