使用Borland 2007和Indy UDP服务器和客户端考虑以下最小程序:
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个字节?
其次发生在x和y上的是什么?
当我将t,x,y的数据类型更改为short时,我得到:
sent 6
received 4
3 2 0
环顾四周,我发现结构的包装(可能还有字节序?)很重要,但我找不到如何正确设计它的明确指南。
答案 0 :(得分:2)
TBytes
是一个动态的字节数组,它由RTL实现为指针,这就是sizeof(AData)
返回的原因4.不要使用sizeof(AData)
,使用{{ 1}}属性改为:
AData.Length