0

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.

Open Kastle
  • 427
  • 3
  • 13
Miren
  • 1
  • 1
  • you're going to need to invent a protocol. And please for pity's sake, don't store pointers in std::containers. Store objects. – Richard Hodges Apr 12 '16 at 20:50

1 Answers1

1

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.

Open Kastle
  • 427
  • 3
  • 13