3

I am using boost::asio::streambuf to write a ostream to my boost socket.

Name name;
name.set_name("platzhirsch");

boost::asio::streambuf b;
std::ostream os(&b);

ZeroCopyOutputStream *raw_output = new OstreamOutputStream(&os);
CodedOutputStream *coded_output = new CodedOutputStream(raw_output);

coded_output->WriteVarint32(name.ByteSize());
name.SerializeToCodedStream(coded_output);

socket.send(b.data());

However, size_t returned by send is 0. I am suspicious that no data is sent at all. Also because the client socket throws horrible exceptions. I am asking, if there is something strange about my code.

In other words, can I test if streambuf is empty or if the data written to it is really there.

Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143

2 Answers2

3

Not sure about your code. This works for me:

    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET " << queryArgs << " HTTP/1.0\r\n";
    request_stream << "Host: " << serverIp  /* "192.168.0.70" */ << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    boost::asio::write(socket, request);
Bob Yoplait
  • 2,421
  • 1
  • 23
  • 35
1

It was no problem of boost::asio, it was a problem of Google protobuf.

In order to flush the CodedOutputStream, they have to be deleted:

ZeroCopyOutputStream *raw_output = new OstreamOutputStream(&os);
CodedOutputStream *coded_output = new CodedOutputStream(raw_output);

coded_output->WriteVarint32(name.ByteSize());
name.SerializeToCodedStream(coded_output);

delete coded_output;
delete raw_output;

socket.send(b.data());
Konrad Reiche
  • 27,743
  • 15
  • 106
  • 143
  • 1
    You do not have to allocate the streams dynamically, but can use blocks to control the lifetime of stack objects instead. See http://stackoverflow.com/a/20397980/891439 for a complete answer. I've only added this comment for completeness, since I've had to google a lot to find a solution. – Florian Wolters Dec 05 '13 at 10:53
  • @FlorianWolters Feel free to add your own answer. I am happy to accept another answer, but mine. – Konrad Reiche Dec 05 '13 at 12:10
  • I think the comment is sufficient, but ty! – Florian Wolters Dec 05 '13 at 13:10