C ++中的网络协议对象序列化 [英] Network protocol object serialization in C++
问题描述
我正在编写一些C ++代码,这些代码必须通过TCP / IP发送数据。我希望此代码在Linux / Windows / Osx上可移植。现在,因为这是我第一次编写可移植的网络代码,所以我基本上需要一些简单的函数来添加某些对象,例如:
I'm writing some C++ code that will have to send data over TCP/IP. I want this code to be portable on Linux/Windows/Osx. Now, as it is the first time I write portable network code, I basically need some simple functions to add to certain objects like:
class myclass{
...member...
public:
string serialize(){
std::ostringstream out();
out << member1;
out << member2;
out << member3;
return out.str();
}
}
...这就是我现在需要。无论如何,我开始阅读与ostringstream相关的文档,并发现了二进制/文本问题。实际上,它将换行符转换为每个系统的正确顺序。例如,假设成员是指向const char * foo = Hello\nMan\n的指针,那么它将在linux上以某些字节顺序转换,在Windows上以另一个字节顺序转换,依此类推。我的字节将通过互联网发送到一个数据包中,另一台OS机器将读取它们,并且我认为会发生麻烦...现在,我读到我可以用<初始化 ostringstream
code> ostringstream(ios :: bin) ...是否可以解决问题(前提是我将使用反序列化函数,该函数将使用 istringstream( ios :: bin)
???我对整个图片感到困惑,如果您花一些澄清的行将不胜感激。
... which is all I need for now. Anyway I started reading ostringstream related docs and turns out the binary/text problem. In fact it will convert line breaks to the right sequence of everysystem. Suppose for example that a member is a pointer to const char* foo = "Hello\nMan\n", that will be translated in certain byte sequence on linux, another on windows... and so on. My bytes will go on a packet over the internet, a different OS machine will read them and I think trouble will occurr... Now I read that I might initialize ostringstream
with ostringstream(ios::bin)
... Will it solve the problem (provided that I will use a de-serialization function that will use a istringstream(ios::bin)
??? I'm confused about the whole picture, if you may spend a few clarifying lines that'll be much appreciated.
谢谢。
推荐答案
如果有像可以构建的Boost.Serialization ?
从目标出发:
数据可移植性-在一个平台上创建的字节流应可在任何其他平台上读取。
Data Portability - Streams of bytes created on one platform should be readable on any other.
您也可能感兴趣的点4和5:
Also of interest for you might be points 4 and 5:
- 深层指针的保存和恢复。即,指针的保存和恢复可以保存和恢复指向的数据。
- 正确恢复共享数据的指针。
这篇关于C ++中的网络协议对象序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!