Serialize vector in C++ to send over UDP Socket?

2019-06-14 17:41发布

As a part of our end semester project we are required to implement a distributed chat system. The system needs to be scalable and robust. Keeping these criteria in mind I am confused as to how do we send a vector object over the socket.

Since the vector is dynamically allocated sending it's object as such would not work as the memory to which it points is not copied. In order to accomplish this serialization would be the best option. But, as required by our project we are not suppose to use any third party libraries such as Boost and Google Protocol Buffers.

Hence to serialize the vector object and send it over the network I cannot seem to find a starting guide explaining how to proceed. Also are there any other alternatives that we can use for this ?

The vector would be containing strings(IP Address:Port) of each member in the chat group.

Any help would be great. Thank You.

NOTE: We are required to make the chat client run on a cluster and I believe in order to make the system robust and scalable we need to take into account the endianess also.

1条回答
做自己的国王
2楼-- · 2019-06-14 18:15

If you want binary serialization in this case, you need to implement serialization for 2 types -- integer and string. Integer can be easily written byte by byte, by casting it to char and then shifting:

// assuming 32 bit ints and 8 bit bytes
int integer = 1337;
unsigned char data[4];
for(int i = 0; i < 4; ++i)
    data[i] = (unsigned char) (integer >> 8*i);

Deserialize by sum and shift:

int integer = 0;
for(int i = 3; i >= 0; ++i)
{
    integer += data[i];
    integer <<= 8;
}

(I didn't test the code, so trace through it in a debugger and make sure it does what I think it does :))

Serialized string would be serialized size and then characters on the stream.

Vector would then be a combination of those 2 -- size of vector, then strings one by one.

You might want to add magic word and checksum to make sure client know what to expect and how to verify the data. If you want to get really fancy, implement your own backing for ASN.1 or something. :)

查看更多
登录 后发表回答