2

I would like to serialize instances of a class and send them over TCP connection using C++ / Boost libraries. There are too many working examples out there... Some using text streams for buffers and some using tcp::iostream. I'm not sure which one is suitable for my needs.

Requirements:

  1. Portability over different architectures (endiannes and bitness should not be a problem)
  2. Data need to be in binary format. (There is no text)

Current code:

// Client side:
boost::asio::streambuf b;
std::ostream os(&b);
boost::archive::binary_oarchive oa(os);
message m; // The `message' class is serializable
// construct `m'
oa << m;
boost::asio::write(socket,b.data(),boost::asio::transfer_all());

// Server side:
boost::asio::streambuf b;
std::istream is(&b);
boost::archive::binary_iarchive ia(is);
boost::asio::read(socket,b,boost::asio::transfer_all());
message m;
ia >> m;

Which is not working. Server exits with invalid signature exception.

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
sorush-r
  • 10,490
  • 17
  • 89
  • 173

1 Answers1

0

Are you required to use Boost? It looks like there's a similar SO question here - There's a response that references the Boost Serialization TODO section (here's the latest) - it looks like a portable binary archive is still on the author's TODO list, so I'm not sure there's a Boost solution (yet) that satisfies your requirements.

You might consider using a Boost text serialization archive anyway, even though your classes aren't text-based. The downside to this is that it is slower and the serialized format is more bloated, but it will be portable.

Alternatives to look at:

  • Google Protocol Buffers (GPB) - this library is intended for platform-independent and language-independent communication. Instead of creating the 'message' class and defining serialization, you define an item in the GPB specification language, and GPB provides tools to parse that specification and generate code to marshall/unmarshall that item
  • SLICE - similar to GPB, but with a richer specification language

Hopefully this gives you some new ideas to look at.

Community
  • 1
  • 1
Tom
  • 2,369
  • 13
  • 21
  • I'm trying to write portable code (as most as possible). That's the reason to use boost. Currently I can ignore binary portability over architectures. Though above even didn't run on same machine... I need help about *Binary Serialization with Boost ASIO/Serialization* anyway. – sorush-r May 18 '13 at 05:24
  • So I accept this answer and ask another [SO question](http://stackoverflow.com/questions/16621317/serializing-binary-data-in-boost-fails-with-invalid-signature-error). Thanks – sorush-r May 18 '13 at 06:22
  • 2
    I will downvote this answer as I am interested in what the OP asked, and you went down a totally different path. How about "answering the question that was asked"?? – CashCow Jul 17 '17 at 12:51