你可以像这样声明一个静态无符号字符:
#define MSGBUFSIZE 512
static unsigned char ClientSendBuf[MSGBUFSIZE];
然后像这样将你的结构复制到数组中:
memmove(&ClientSendBuf[2], &struct, sizeof(struct));
现在这是下一个特定于实现的地方。我正在使用 Borland C++,所以我的发送行为如下:
ClientSocket->Socket->SendBuf(ClientSendBuf, ClientSendBuf[0]+CRC16SIZE);
我使用 ClientSendBuf[0] 的原因是因为我的消息大小存储在 ClientSendBuf[0] 中,如下所示:
ClientSendBuf[0] = 4 + sizeof(struct); //Byte Count
(注意:将 struct 替换为您的 struct 的名称)
我还在消息末尾添加了一个 CRC 检查,如下所示:
#define CRC16SIZE 2
...
cs = CheckSum((unsigned char *)ClientSendBuf, ClientSendBuf[0]);
memmove(&ClientSendBuf[ClientSendBuf[0]], &cs, CRC16SIZE);
...
unsigned short __fastcall TFormMenu::CheckSum(unsigned char *p, int length)
{
int i;
for (cs = 0, i = 0; i < length; i++) {
cs += p[i];
}
return cs;
}
基本上,所有这些简单的 CRC 校验所做的都是对所有字节求和,以确定发送的字节数是否正确。如果数据被破坏(顺便说一句,这在有问题的 WiFi 连接中很常见),那么服务器应该抛出一个 CRC 错误。
这一切都假设你有一个 POD 结构。 static 部分不是必需的,但我在特定应用程序中是如何做到的。我还掩盖了一些细节。如果您有任何问题,请在 cmets 中发帖。 YMMV。