通过Indy UDP正确发送和接收结构 [英] Correctly sending and receiving a struct through Indy UDP
问题描述
考虑使用Borland 2007和Indy UDP服务器和客户端的以下最小程序:
Consider the following minimal program using Borland 2007 and Indy UDP server and client:
struct DATA_PACKAGE
{
int t;
int x;
int y;
};
void __fastcall TForm1::Button1Click(TObject *Sender)
{
DATA_PACKAGE a;
a.t = 3;
a.x = 2;
a.y = 1;
Form1->Memo1->Lines->Add("sent " + IntToStr(sizeof(DATA_PACKAGE)));
Form1->UDPClient1->SendBuffer(server,port,RawToBytes(&a, sizeof(DATA_PACKAGE)));
}
void __fastcall TForm1::UDPServer1UDPRead(TObject *Sender, TBytes AData,
TIdSocketHandle *ABinding)
{
DATA_PACKAGE r;
Form1->Memo1->Lines->Add("received " + IntToStr(sizeof(AData)));
BytesToRaw(AData, &r, sizeof(AData));
Form1->Memo1->Lines->Add(IntToStr(r.t) + " " + IntToStr(r.x) + " " + IntToStr(r.y));
}
输出:
sent 12
received 4
3 4717901 0
首先,为什么它发送12个字节,但只接收4个字节?
First of all, why is it sending 12, but only receiving 4 bytes?
第二,x和y发生了什么?
Secondly what happends to x and y ?
当我将t,x,y的数据类型更改为short时,我得到:
When I change the datatype of t,x,y to short, I get:
sent 6
received 4
3 2 0
环顾四周,我发现指针指出了该结构的包装(或可能是字节序?)很重要,但是我找不到一个明确的指南来正确设计它.
looking around I found pointers that the packing (and possibly the endianness?) of the struct is of importance, I could however not find a clear guide how design it properly.
推荐答案
TBytes
是动态字节数组,由RTL作为指针实现,这就是sizeof(AData)
返回4的原因.请勿使用sizeof(AData)
,请改用AData.Length
属性:
TBytes
is a dynamic array of bytes, it is implemented by the RTL as a pointer, which is why sizeof(AData)
is returning 4. Do not use sizeof(AData)
, use the AData.Length
property instead:
void __fastcall TForm1::UDPServer1UDPRead(TObject *Sender, TBytes AData,
TIdSocketHandle *ABinding)
{
DATA_PACKAGE r;
Form1->Memo1->Lines->Add("received " + IntToStr(AData.Length));
BytesToRaw(AData, &r, AData.Length);
Form1->Memo1->Lines->Add(IntToStr(r.t) + " " + IntToStr(r.x) + " " + IntToStr(r.y));
}
这篇关于通过Indy UDP正确发送和接收结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!