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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
So I accept this answer and ask another SO question. Thanks
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"??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.