序列化向量在C ++中通过UDP发送Socket? [英] Serialize vector in C++ to send over UDP Socket?

查看:520
本文介绍了序列化向量在C ++中通过UDP发送Socket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为我们的结束学期项目的一部分,我们需要实现一个分布式聊天系统。系统需要可扩展和稳健。记住这些标准我很困惑我们如何通过套接字发送一个向量对象。

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.

由于向量是动态分配的,发送它的对象,因为它不会作为它指向的内存不会被复制。为了完成这个序列化将是最好的选择。但是,根据我们的项目要求,我们不假设使用任何第三方库,如Boost和Google协议缓冲区。

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 ?

向量将包含聊天组中每个成员的字符串(IP地址:端口)

任何帮助将是巨大的。谢谢。

Any help would be great. Thank You.

注意:我们需要让聊天客户端在集群上运行,我相信为了使系统稳定可扩展,我们需要考虑也就是endianess。

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.

推荐答案

如果在这种情况下需要二进制序列化,您需要为两种类型 - 整数和字符串实现序列化。整数可以容易地逐个字节写入,通过将其转换为char然后移位:

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);

通过sum和shift进行反序列化:

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.

然后向量将是那些2 - 大小的向量,然后是字符串一个接一个的组合。

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

您可能需要添加魔术字和校验和,以确保客户端知道预期内容以及如何验证数据。如果你想真的想,实现自己的支持ASN.1或东西。 :)

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

这篇关于序列化向量在C ++中通过UDP发送Socket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆