gpt4 book ai didi

delphi - Indy UDP读取Adata的内容

转载 作者:行者123 更新时间:2023-12-02 13:32:16 27 4
gpt4 key购买 nike

我正在使用 Indy UDP Server 读取一串数据。但是,我真的不知道如何使用 Adata 参数。我可以通过使用下面的 ByteToBin 函数将其转换为二进制,然后使用 BintoHex1 将其转换为十六进制来解决这个问题。但我真的觉得这真的很愚蠢,而且效果很慢。有谁知道如何在没有这两次转换的情况下直接获得结果?

谢谢!!

代码如下:

procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread;
const AData: TIdBytes; ABinding: TIdSocketHandle);
var
Buf: TIdBytes;
buffer: string;
Data_received: string;
begin
if bytestostring(AData) <> 'Hello' then
begin
buffer := HextoString('00');
SetLength(Buf, Length(buffer));
CopyTIdString(buffer, Buf, 0);
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, Buf);

Data_received := BinToHex1(ByteToBin(AData[1]) + ByteToBin(AData[2]) +
ByteToBin(AData[3]) + ByteToBin(AData[4]) + ByteToBin(AData[5]) +
ByteToBin(AData[6]) + ByteToBin(AData[7]) + ByteToBin(AData[8]) +
ByteToBin(AData[9]) + ByteToBin(AData[10]) + ByteToBin(AData[11]) +
ByteToBin(AData[12]));

end;
memo1.Lines.Add(Data_received);
Memo1.GoToTextEnd;
end;

function TForm1.ByteToBin(aByte: byte): String;
Const
c10: Array [Boolean] of Char = ('0', '1');
Var
eLoop1: byte;
Begin
SetLength(Result, 8);
For eLoop1 := 7 downto 0 do
Result[8 - eLoop1] := c10[(aByte and (1 shl eLoop1)) <> 0];
End;

function TForm1.BinToHex1(BinStr: string): string;
const
BinArray: array [0 .. 15, 0 .. 1] of string = (('0000', '0'), ('0001', '1'),
('0010', '2'), ('0011', '3'), ('0100', '4'), ('0101', '5'), ('0110', '6'),
('0111', '7'), ('1000', '8'), ('1001', '9'), ('1010', 'A'), ('1011', 'B'),
('1100', 'C'), ('1101', 'D'), ('1110', 'E'), ('1111', 'F'));
var
Error: Boolean;
j: Integer;
BinPart: string;
begin
Result := '';

Error := False;
for j := 1 to Length(BinStr) do
if not(BinStr[j] in ['0', '1']) then
begin
Error := True;
ShowMessage('This is not binary number');
Break;
end;

if not Error then
begin
case Length(BinStr) mod 4 of
1:
BinStr := '000' + BinStr;
2:
BinStr := '00' + BinStr;
3:
BinStr := '0' + BinStr;
end;

while Length(BinStr) > 0 do
begin
BinPart := Copy(BinStr, Length(BinStr) - 3, 4);
Delete(BinStr, Length(BinStr) - 3, 4);
for j := 1 to 16 do
if BinPart = BinArray[j - 1, 0] then
Result := BinArray[j - 1, 1] + Result;
end;
end;
end;

最佳答案

您的代码过于复杂。 Indy 的 IdGlobal 单元中有许多用于处理 TIdBytes 数据的函数。例如,您可以将示例简化为以下内容:

procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread;
const AData: TIdBytes; ABinding: TIdSocketHandle);
begin
if BytesToString(AData) <> 'Hello' then begin
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, ToBytes(Byte(0)));
end;
memo1.Lines.Add(ToHex(AData));
Memo1.GoToTextEnd;
end;

关于delphi - Indy UDP读取Adata的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167142/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com