序列化和使用Boost发送的数据结构? [英] Serialize and send a data structure using Boost?

查看:202
本文介绍了序列化和使用Boost发送的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构,看起来像这样:

I have a data structure that looks like this:


typedef struct
{
  unsigned short m_short1;
  unsigned short m_short2;
  unsigned char m_character;
} MyDataType;

我想使用boost ::序列化序列化这种数据结构,然后使用boost :: ASIO通过TCP / IP传输,然后有另一个应用程序接收数据,并使用相同的Boost库它​​反序列化。

I want to use boost::serialization to serialize this data structure, then use boost::asio to transmit it via TCP/IP, then have another application receive the data and de-serialize it using the same boost libraries.

我想下面的boost ::序列化教程其他一些SO问题建议),但例子是专门为书写/使用boost :: ASIO读取一个文件,而不是一个套接字。

I'm trying to following boost::serialization tutorial, (as some other SO questions have suggested) but the example is specifically for writing/reading to a file, not to a socket using boost::asio.

我是pretty肯定我明白了这个职位的合适的工具 - 我只是需要帮助使他们一起工作。写套接字无法从写入文件,不同的,对吧?

I'm pretty sure I've got the right tools for the job -- I just need help making them work together. Writing to a socket can't be that different from writing to a file, right?

任何建议都非常AP preciated。谢谢!

Any suggestions are very much appreciated. Thanks!

推荐答案

对于这样简单的结构,提高::序列化是大材小用和巨大开销。

For such simple structure, boost::serialization is overkill and huge overhead.

做简单:

vector<uint16_t> net(3,0);

net[0]=htons(data.m_short1);
net[1]=htons(data.m_short2);
net[2]=htons(data.character);

asio::async_write(socket,buffer((char*)&net.front(),6),callback);

vector<uint16_t> net(3,0);
asio::async_read(socket,buffer((char*)&net.front(),6),callback);

callback:
data.m_short1=ntohs(net[0]);
data.m_short2=ntohs(net[1]);
data.character=ntohs(net[2]);

和保存自己,提升巨大的开销::序列有

And Save yourself HUGE overhead that boost::serialization has

如果你的私人协议,其中与字节的工作顺序相同的计算机(大/小)
这只是发送结构是 - POD

And if you private protocol where computers with same order of bytes work (big/little) that just send structure as is -- POD.

这篇关于序列化和使用Boost发送的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆