开发者

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 serializat开发者_Python百科ion 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.


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


What about using ostringstream?

ostringstream oss;

oss << "hello world";

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜