foobarfuzzbizz
foobarfuzzbizz

Reputation: 58657

How can I serialize and send a std::list over the network?

I need to send a dynamically sized list of data stored inside a std::list over a network connection. I would like to do this in one pass using serialization, rather than sending each element individually. Any suggestions?

Upvotes: 3

Views: 3224

Answers (2)

boost::serialization makes this fairly easy to do. It provides all of the mechanics you need for std::list for free, all you will need to do is add support to the type your list holds. (If it's a "standard" type this will already exist too)

Complete example (adapted from this example):

#include <list>
#include <sstream>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
// Provide an implementation of serialize for std::list
#include <boost/serialization/list.hpp>

class foo
{
private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/)
  {
    // This is the only thing you have to implement to serialize a std::list<foo>
    ar & value;
    // if we had more members here just & each of them with ar
  }
public:
  int value;
};

int main() {
  std::stringstream out;

  // setup a list
  std::list<foo> list;
  {
    const foo f = {-1};
    list.push_back(f);
  }

  // serialize into the stream
  {
    boost::archive::binary_oarchive oa(out);
    oa << list;
  }

  // read the stream into a newlist
  std::list<foo> newlist;
  {
    boost::archive::binary_iarchive ia(out);
    ia >> newlist;
  }

  std::cout << newlist.front().value << std::endl;
}

This "sends" and "receives" via a std::stringstream, but it should be fairly trivial to adapt this to send and receive via the network API of your choice.

Upvotes: 5

JosephH
JosephH

Reputation: 8815

Use xerces-C++ to convert to/from XML and send/receive it.

Upvotes: 0

Related Questions