正如我在对你的评论中告诉你的上一个问题 https://stackoverflow.com/q/27129331:
你必须使用一个TIdBytes
也为此。使用SetLength()
将其预先分配到所需的大小,然后调用ReceiveBuffer()
有了它,然后您可以根据需要直接或使用它复制数据BytesToRaw()
.
例如:
private
myBuf: TIdBytes;
...
while not Terminated do
begin
try
SetLength(myBuf, buffLength);
lenUDP := IdUDPClient.ReceiveBuffer(myBuf, -1);
if lenUDP > 0 then
begin
SetLength(myBuf, lenUDP);
Synchronize(ReceivedLine);
end;
except
Terminate;
end;
end;
由于您的原始缓冲区是一个数组Char
,你的处理函数被命名为ReceivedLine()
,我假设您的数据本质上是文本数据。如果这是真的,您可以使用BytesToString()
or (T|I)IdTextEncoding.GetString()
转换一个TIdBytes
to a String
,如果是这样的话ReceivedLine()
uses myBuf
例如:
S := BytesToString(myBuf{, en8bit});
S := BytesToString(myBuf, 0, lenUDP{, en8bit});
S := IndyTextEncoding_8bit.GetString(myBuf);
S := IndyTextEncoding_8bit.GetString(myBuf, 0, lenUDP);
您可以通过各种方式使用 Indy 支持的任何字符集编码en...()
, Indy...Encoding()
, or IndyTextEncoding...()
中的函数IdGlobal
单位,或CharsetToEncoding()
函数在IdGlobalProtocols
unit.
UPDATE:由于您的缓冲区是其中包含联合的记录的一部分,因此您必须使用本地TIdBytes
变量代替:
type
myRecord = record
...
myBuf: array[0..buffLength-1] of Byte;
...
end;
...
private
myRec: myRecord;
...
var
udpBuf: TIdBytes;
...
SetLength(udpBuf, buffLength);
while not Terminated do
begin
try
lenUDP := IdUDPClient.ReceiveBuffer(udpBuf, -1);
if lenUDP > 0 then
begin
BytesToRaw(udpBuf, myRec.myBuf[0], lenUDP);
Synchronize(ReceivedLine);
end;
except
Terminate;
end;
end;