如何通过网络序列化和发送 std::list?
我需要通过网络连接发送存储在 std::list 中的动态大小的数据列表.我想使用序列化一次性完成此操作,而不是单独发送每个元素.有什么建议吗?
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?
boost::serialization
使这很容易做到.它免费提供了 std::list
所需的所有机制,您需要做的就是添加对列表类型的支持.(如果它是标准"类型,它也已经存在)
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)
完整示例(改编自这个示例):
#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;
}
这通过std::stringstream
发送"和接收",但调整它以通过您选择的网络API发送和接收应该是相当简单的.
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.