简体   繁体   English

组合多个变量以作为udp数据包发送

[英]Combine multiple variables to send as a udp packet

I need to send a packet of data over a UDP connection in C++. 我需要通过C ++中的UDP连接发送数据包。 The first message I need to send is built up of two 32 bit integers and a 64 bit integer. 我需要发送的第一条消息由两个32位整数和一个64位整数构成。 What is the best way to combine multiple variable types into one block of data ready for sending over a UDP connection? 将多个变量类型组合成一个数据块以便通过UDP连接发送的最佳方法是什么?

It depends on the requirements for your network. 这取决于您的网络要求。 Do you care about endianness? 你关心字节序吗? If you do, you should use not just any serialisatioin, but a safe one in regards to endianness. 如果你这样做,你不应该使用任何序列化,而应该使用关于字节序的安全序列。

Generally, each class/struct sendable through the network should have special methods or overloaded operators to stream them in and out. 通常,通过网络可发送的每个类/结构应该具有特殊方法或重载运算符以将它们流入和流出。 Ultimately you'll have to use macros/functions like hton/ntoh for streaming primitive types eg int, int64, float, double etc. 最终你必须使用像hton / ntoh这样的宏/函数来传输基本类型,例如int,int64,float,double等。

Upd: also if your network endpoint applications run on different platforms/compilers, you may have different sizes of int, long, short etc. So when serialising, you'll have to convert your integers to some predefined types with sizes guaranteed to be the same on all supported platforms. 更新:如果您的网络端点应用程序在不同的平台/编译器上运行,您可能有不同的int,long,short等大小。因此,在序列化时,您必须将整数转换为某些预定义类型,其大小保证为所有支持的平台都一样。

I wrote a DNS resolver by hand in C, and structs is indeed the way I did it. 我用C手工编写了一个DNS解析器,结构确实是我做的方式。 Use bit fields to specify sizes of each piece. 使用位字段指定每个部分的大小。 More about bit fields: http://msdn.microsoft.com/en-us/library/ewwyfdbe.aspx 有关位字段的更多信息: http//msdn.microsoft.com/en-us/library/ewwyfdbe.aspx

Make sure to use hton/ntoh to take care of byte order. 确保使用hton / ntoh来处理字节顺序。 More information here; 更多信息在这里; http://www.beej.us/guide/bgnet/output/html/multipage/htonsman.html http://www.beej.us/guide/bgnet/output/html/multipage/htonsman.html

In fact, peruse beej's guide -- mucho useful information there! 事实上,仔细阅读beej的指南 - 那里有很多有用的信息!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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