Search code examples
c++network-programmingboost-asioboost-serialization

Which stream is suitable for serialization over UDP?


I am trying to serialize and recover objects over UDP using the Boost.Serialization and Boost.Asio libraries. The following points sum up what I know so far:

  • The main concept of Boost.Serialization is the archive. An archive is a sequence of bytes that represent serialized C++ objects.
  • The class boost::archive::text_oarchive serializes data as a text stream, and the class boost::archive::text_iarchive restores data from such a text stream.
  • Constructors of archives expect an input or output stream as a parameter. The stream is used to serialize or restore data.

source: https://theboostcpplibraries.com/boost.serialization-archive

I understand that I must pass a stream as a parameter to the archive. However, there are a few different types of streams which are suitable candidates. See the following digram:

stream types

source: https://stackoverflow.com/a/8116698/3599179

I have seen online serialization examples that used ostream and istream, other examples used ostringstream and istringstream and some others used streambuf, which acts as both an input and output buffer if I am not mistaken.

(File streams are out of the equation because I need to write/read from a socket not from a file.)

  • What advantages/disadvantages offer each of the aforementioned streams?
  • Considering that I must send the serialized objects over UDP, which stream is the best candidate?

Solution

  • Take time to read descriptions of the streams you mentioned on cppreference.com Input/output library, it is quite instructive.

    If you want to serialize into memory only one stream works for you: ostringstream. Then you extract the string from it and send it however you please. For deserialization use istringstream. Alternatively, stringstream for both cases.