简体   繁体   中英

How to serialize a list into an array of chars

I have a list defined as:

list<Message*> g_messages;

where Message is:

struct Message {

    static unsigned int s_last_id; 
    string user_name;
    string content;
    unsigned int id;
};

My objective is to send this information using Winsock (from server to client), but this only allows sending chars as it appears in WinSock2.h. Taking this into account, I want to serialize all the information ( id , content and user_name ) in an array of chars in order to send it all together, and in the client, have a function to deserialize so as to have the same vector I had in the server.

How could I implement it?

Any help is appreciated.

You have a couple of options, there isn't a single trivial solution for this. You will have to design your own protocol that the server and client can agree on with regards to serializing and deserializing to and from the socket stream.

One characteristic of your Message that makes this a little tricky is that, when flattened to a character array, it results in an array which is a variable length since the Message 's strings are variable length. So there will be some amount of interpretation on the client side since it cannot assume bytes 0-2 correspond to X and so forth.

One approach you might take is to write all of your data members to a string stream with each data member separated by a delimiter, spaces maybe:

std::ostringstream oss;
oss << s_last_id << " " << user_name << " " << content << " " << id;

And then when writing to the socket:

std::string messageString = oss.str();
std::vector<char> writable(begin(messageString), end(messageString));
char* c = &writable[0];

send(socket, c, writable.size(), 0);

On the client side, you could then parse the incoming character array into the corresponding data members:

char recvBuf[bufMax];
recv(socket, recvBuf, bufMax, 0);

std::istringstream iss(std::string(recv));
iss >> s_last_id >> user_name >> content >> id;

It may not be the most performant solution, but it's pretty simple and may work fine for your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM