正确使用IdUDPClient.ReceiveBuffer [英] Proper use of IdUDPClient.ReceiveBuffer
问题描述
感谢您的帮助。
我正在将较早版本的Delphi转换为XE5,并且我对Indy组件感到困惑。需要使用IdUDPClient.ReceiveBuffer
I am converting an older version of Delphi to XE5 and I am getting stuck with the Indy compnent. Need to use IdUDPClient.ReceiveBuffer
这是我的代码:
while not Terminated do
begin
try
lenUDP:= IdUDPClient.ReceiveBuffer(myBuf, buffLength, -1 );
if lenUDP<> 0 then
Synchronize(ReceivedLine);
except
Terminate;
end;
end;
其中,
myBuf =字符的压缩数组[0 .. buffLength -1];
where, myBuf = packed array [0 .. buffLength -1] of char;
非常感谢所有帮助。
谢谢,
迈克
推荐答案
正如我在对上一个问题:
您必须使用
TIdBytes
也是如此。使用SetLength()
将其预分配为所需的大小,然后调用ReceiveBuffer()
,然后您可以根据需要直接或使用BytesToRaw()
复制数据。
You have to use a
TIdBytes
for that as well. UseSetLength()
to pre-allocate it to the desired size, then callReceiveBuffer()
with it, and then you can copy out data from it as needed, either directly or withBytesToRaw()
.
例如:
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()
或(T | I)IdTextEncoding.GetString()
进行转换 TIdBytes
到 String
,如果那是 ReceivedLine()
将 myBuf
用于例如:
Since your original buffer was an array of Char
, and your processing function is named ReceivedLine()
, I am assuming your data is textual in nature. If that is true, you can use BytesToString()
or (T|I)IdTextEncoding.GetString()
to convert a TIdBytes
to a String
, if that is what ReceivedLine()
uses myBuf
for, eg:
S := BytesToString(myBuf{, en8bit});
S := BytesToString(myBuf, 0, lenUDP{, en8bit});
S := IndyTextEncoding_8bit.GetString(myBuf);
S := IndyTextEncoding_8bit.GetString(myBuf, 0, lenUDP);
您可以通过各种 en使用Indy支持的任何字符集编码...()
, Indy ... Encoding()
或 IndyTextEncoding ...()$
IdGlobal
单元中的c $ c>函数,或中的
单位。 CharsetToEncoding()
函数IdGlobalProtocols
You can use any charset encoding that Indy supports, either via the various en...()
, Indy...Encoding()
, or IndyTextEncoding...()
functions in the IdGlobal
unit, or the CharsetToEncoding()
function in the IdGlobalProtocols
unit.
更新:由于缓冲区是带有联合的记录的一部分,因此您将必须使用局部 TIdBytes
变量:
UPDATE: since your buffer is part of a record with a union in it, you will have to use a local TIdBytes
variable instead:
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;
这篇关于正确使用IdUDPClient.ReceiveBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!