How to serialize an object to send over network

前端 未结 5 1173
陌清茗
陌清茗 2021-02-15 17:42

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

5条回答
  •  梦谈多话
    2021-02-15 17:58

    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().

    Look.

    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
    }
    

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

提交回复
热议问题