【发布时间】:2009-02-16 18:41:17
【问题描述】:
问题:我正在寻找的是最典型或最佳实践在 Indy 10 中使用 IdTCPClient 使用单独线程接收数据的方法。 p>
背景: 下面的代码是我尝试删除的实际数据处理部分的示例,为清楚起见。线程的想法是接收所有数据(带有声明其余消息长度的标头的可变大小)然后解析它(这就是 HandleData 过程所做的)并根据命令触发事件处理程序。
TIdIOHandlerSocket 由主应用程序传递给线程,主应用程序也会在需要时将数据写入套接字。
TScktReceiveThread = class(TThread)
private
{ Private declarations }
procedure HandleData;
protected
procedure Execute; override;
public
FSocket: TIdIOHandlerSocket;
constructor Create(CreateSuspended: boolean);
end;
procedure TScktReceiveThread.Execute;
var
FixedHeader: TBytes;
begin
Assert(FSocket <> nil, 'You must assign the connected socket to the receiving thread');
SetLength(FixedHeader, 2);
while not Terminated do
begin
if not FSocket.Connected then
Suspend
else
begin
FSocket.CheckForDataOnSource(10);
if not FSocket.InputBufferIsEmpty then
begin
FSocket.ReadBytes(FixedHeader, SizeOf(FixedHeader), false);
// Removed the rest of the reading and parsing code for clarity
Synchronize(HandleData);
end;
end;
end;
end;
作为前缀,我使用了另一个处理 Indy 的服务器组件的 StackOverflow 问题:“Delphi 2009, Indy 10, TIdTCPServer.OnExecute, how to grab all the bytes in the InputBuffer”来了解我目前所拥有的基础。
感谢您的帮助!
【问题讨论】:
标签: multithreading delphi sockets indy