如何序列化对象以通过网络发送
我正在尝试序列化对象,以仅使用STL通过套接字通过网络发送.我没有找到一种方法来保持对象结构在其他主机中反序列化.我尝试转换为 string
,转换为 char *
,并且花了很长时间在互联网上搜索教程,直到现在我仍然一无所获.
I'm trying to serialize objects to send over network through a socket using only STL. I'm not finding a way to keep objects' structure to be deserialized in the other host. I tried converting to string
, to char*
and I've spent a long time searching for tutorials on the internet and until now I have found nothing.
是否只有STL可以做到?
Is there a way to do it only with STL?
有什么好的教程吗?
我几乎要尝试增强功能,但是如果有使用STL的方法,我想学习.
I am almost trying boost, but if there is how to do it with STL I'd like to learn.
我明白了!
我使用strinstream序列化对象,并使用stringstream的str()方法和字符串的c_str()将其作为消息发送.
I used strinstream to serialize objects and I sent it as a message using the stringstream's method str() and so string's c_str().
看.
class Object {
public:
int a;
string b;
void methodSample1 ();
void methosSample2 ();
friend ostream& operator<< (ostream& out, Object& object) {
out << object.a << " " << object.b; //The space (" ") is necessari for separete elements
return out;
}
friend istream& operator>> (istream& in, Object& object) {
in >> object.a;
in >> object.b;
return in;
}
};
/* Server side */
int main () {
Object o;
stringstream ss;
o.a = 1;
o.b = 2;
ss << o; //serialize
write (socket, ss.str().c_str(), 20); //send - the buffer size must be adjusted, it's a sample
}
/* Client side */
int main () {
Object o2;
stringstream ss2;
char buffer[20];
string temp;
read (socket, buffer, 20); //receive
temp.assign(buffer);
ss << temp;
ss >> o2; //unserialize
}
我不确定在序列化之前是否有必要转换为字符串(ss< o),也许可以直接从char中获得.
I'm not sure if is necessary convert to string before to serialize (ss << o), maybe is possible directly from char.