在C ++中序列化/反序列化简单协议的最佳方法 [英] Best way of serializing/deserializing a simple protocol in C++

查看:106
本文介绍了在C ++中序列化/反序列化简单协议的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Linux上使用C ++中的Berkeley套接字构建一个简单的应用程序协议。传输层应该是UDP,协议将包含以下两部分:



第一部分:

它是一个固定的部分,代表协议Header,包含以下字段:

I want to build a simple application protocol using Berkeley sockets in C++ using on Linux. The transport layer should be UDP, and the protocols will contain the following two parts:

The first part:
It is a fixed part which represents the protocol Header with the following fields:

1. int HeaderType
2. int TransactionID
3. unsigned char Source[4]
4. unsigned char Destination[4]
5. int numberoftlvs



第二部分:

它将包含可变数量的TLV,每个TLV将包含以下字段:


The second part:
It will contain variable number of TLVs, each TLV will contain the following fields:

1. int type
2. int length
3. unsigned char *data "Variable length"



我的第一个问题是:

For准备通过网络发送的消息,什么是进行序列化和反序列化的最佳方式,可以在所有系统上移植,如小端和大端?/ $


我应该准备一个unsigned char的大缓冲区,并开始逐个复制字段吗?然后,只需调用send命令?



如果我要按照前面的方式,我怎样才能跟踪指向复制字段的指针,我的猜测是为每个数据类型构建一个函数,该函数将知道移动指针的字节数,对吗?



如果有人能为我提供一个解释良好的例子,非常感谢。



注意:我只想使用C ++ 11的标准库,没有像Boost这样的其他库。



我的第二个问题是:

表示数据类型中IP地址的最佳方法是什么?因为将它表示为字符串将使得不同语言的可移植性变得困难。并且它将在内存中占用更多空间。


My first question is:
For preparing the message to be sent over the wire, what's the best way to do serialization and deserialization, to be portable on all the systems like little Endian and big Endian?

Should I prepare a big buffer of "unsigned char", and start copying the fields one by one to it? And after that, just call send command?

If I am going to follow the previous way, how can I keep tracking the pointer to where to copy my fields, my guess would be to build for each datatype a function which will know how many bytes to move the pointer, correct?

If someone can provide me with a well explained example ,it will much appreciated.

Note: I just want to use the standard library of C++11, no other libraries like Boost.

My second question is:
What is the best way to represent an IP address in a datatype? Because representing it as a string will make it hard for portability for different languages.And it will take more space in the memory.

推荐答案

我建​​议考虑提升序列化: http://www.boost.org/doc/libs/1_55_0/libs/ serialization / doc / index.html [ ^ ]。



这当然是开源的。另请参阅:

http://en.wikipedia.org/ wiki / Boost_%28C%2B%2B_libraries%29 [ ^ ],

http://www.boost.org/ [ ^ ]。



-SA
I would advice considering boost serialization: http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html[^].

This is the open source, of course. Please see also:
http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29[^],
http://www.boost.org/[^].

—SA


这篇关于在C ++中序列化/反序列化简单协议的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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