使用 UDP 协议从 Windows 套接字发送到 Qt 套接字的网络数据包上的结构编码和解码

Structure encoding and decoding on the network packet sent from the Windows Socket to Qt Socket using the UDP Protocol

本文关键字:套接字 数据包 网络 结构 解码 编码 协议 UDP Windows 使用 Qt      更新时间:2023-10-16

如何对从 C++ 套接字发送到 Qt UDP 套接字的结构进行序列化和反序列化

实际上我正在尝试这种逻辑进行序列化和去分离化喜欢这个

struct stCardInfo
{
    unsigned short nsCardType;
    unsigned short nsNoOfSignals;
    unsigned short nsStatus;
};
struct stErrorInfo
{
    unsigned short nsErrorType;
    char ErrorInfo[8];
};
struct stInitHealthCheck
{
    unsigned short nsNoOfCards;
    stCardInfo* lsCardInfo;
};
   stInitHealthCheck stHealthCheck;
   unsigned short *q = (unsigned short *)data;
   stHealthCheck.nsNoOfCards = *q;       q++;
   stHealthCheck.lsCardInfo = new stCardInfo;
   stHealthCheck.lsCardInfo->nsCardType = *q;   q++;
   stHealthCheck.lsCardInfo->nsNoOfSignals = *q;     q++;
   stHealthCheck.lsCardInfo->nsStatus= *q;     q++;

但是如果结构更多,那么我每次解码到特定数据类型将变得复杂且耗时所以我问是否有任何有效的方法来进行序列化和反序列化,以便我可以非常快速地解码和编码发送和接收的UDP数据包

通信设备上的字节序可能不同,在发送/接收unsigned short时应使用 htonsntohs

此外,如果要将结构转换为发送端的char*缓冲区,请注意,这不是编写通信协议的跨平台方式。使用不同的编译器编译代码时,结构在二进制级别可能具有不同的表示形式。

但是,当您有许多已经可用的序列化库时,为什么要弄乱所有这些低级的东西。只需从列表中选择一个!

如果双方都使用Qt,则可以使用QDataStream。您可以查看Qt财富客户端/服务器进行演示。

如果其中一个不使用Qt,你可能想使用JSON(在Qt中支持,并且有许多JSON C++库(。如果您更喜欢二进制格式,则可能需要查看msgpack。