How to serialize an object to send over network

前端 未结 5 1176
陌清茗
陌清茗 2021-02-15 17:42

I\'m trying to serialize objects to send over network through a socket using only STL. I\'m not finding a way to keep objects\' structure to be deserialized in the other host. I

5条回答
  •  灰色年华
    2021-02-15 18:18

    My first question will be: do you want serialization or messaging ?

    It might seem stupid at first, since you asked for serialization, but then I have always distinguished the two terms.

    • Serialization is about taking a snapshot of your memory and restoring it later on. Each object is represented as a separate entity (though they might be composed)
    • Messaging is about sending information from one point to another. The message usually has its own grammar and may not reflect the organization of your Business Model.

    Too often I've seen people using Serialization where Messaging should have been used. It does not mean that Serialization is useless, but it does mean that you should think ahead of times. It's quite difficult to alter the BOM once you have decided to serialize it, especially if you decide to relocate some part of information (move it from one object to another)... because how then are you going to decode the "old" serialized version ?

    Now that that's been cleared up...

    ... I will recommend Google's Protocol Buffer.

    You could perfectly rewrite your own using the STL, but you would end up doing work that has already been done, and unless you wish to learn from it, it's quite pointless.

    One great thing about protobuf is that it's language agnostic in a way: ie you can generate the encoder/decoder of a given message for C++, Java or Python. The use of Python is nice for message injection (testing) or message decoding (to check the output of a logged message). It's not something that would come easy were you to use the STL.

提交回复
热议问题