如何在C ++中通过boost套接字发送ostream?

时间:2011-04-15 10:26:20

标签: c++ sockets stream boost-asio

我在使用protobuf进行进程间通信时遇到了一些问题。 Protobuf允许一组序列化格式:

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

我的问题是,我不知道如何使用我正在使用的提升asio套接字,因为我实现了它们来发送字符串:

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

但我想发送ostream。

2 个答案:

答案 0 :(得分:11)

Boost的asio库与streaduffers级别的std iostream集成

所以写一个请求

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

阅读回复:

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

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

答案 1 :(得分:0)

使用ostringstream怎么样?

ostringstream oss;

oss << "hello world";

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