Lucas Arbiza Lucas Arbiza - 1 year ago 77
C++ Question

How to serialize an object to send over network

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

, to
and I've spent a long time searching for tutorials on the internet and until now I have found nothing.

Is there a way to do it only with STL?

Are there any good tutorials?

I am almost trying boost, but if there is how to do it with STL I'd like to learn.

Answer Source

I got it!

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 {
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
ss << temp;
ss >> o2;   //unserialize

I'm not sure if is necessary convert to string before to serialize (ss << o), maybe is possible directly from char.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download