我有一个C++ struct
用于在服务器之间交换update packet
,另一个struct
来实现有关neighbor
的信息,并且update packet
内部有struct neighbor
vector
。
struct neighbor;
struct update_packet {
uint16_t num_update_fields;
uint16_t port;
uint32_t IP;
vector<struct neighbor> neighbors;
update_packet(char * IPstr, int port) :
num_update_fields(num_nodes),
IP(IP_to_int(IPstr)), port((uint16_t) port)
{ };
};
struct neighbor {
uint32_t IP;
uint16_t port;
int16_t nil;
uint16_t server_id;
uint16_t cost;
neighbor(char * IPstr, uint16_t port, uint16_t server_id, uint16_t cost) :
IP(IP_to_int(IPstr)), port(port), nil(0),
server_id(server_id), cost(cost) { };
};
我想通过UDP
套接字在general message format
中交换这个结构(例如IP datagram
),并在接收端读取消息中的信息。
我怎样才能做到这一点?我的struct
设计对于我的目的来说是一个糟糕的设计吗?
你要问的是序列化。 最简单的是,如果你有一个POD类型,并且知道两端的机器是相同的类型,你可以投射和发送:
struct Foo {
uint32_t a;
uint16_t p;
};
Foo f { 1, 2 };
sendto(targetFD, reinterpret_cast<const char*>(&f), sizeof(f), 0);
由于矢量的原因,您的结构不能以这种方式使用。 向量中的数据是动态分配的,因此它不会与结构的其余部分一起布局。 如果您需要这样的可变长度字段,数组(或 std::array)以及元素数量的指示器将很有用。
像这样的铸造结构速度很快,但并不是真正的便携式。 如果您希望能够传递到其他语言或平台,则更喜欢序列化格式。 Google的Protocol Buffers(https://code.google.com/p/protobuf/)和其他几个序列化库旨在实现这一点。
本文介绍了更多的 c++ 样式序列化和反序列化 - https://rodgert.github.io/2014/09/09/type-driven-wire-protocols-with-boost-fusion-pt1/