問:我正在尋找的是最典型的或最佳的做法是使用一個單獨的線程中印接受使用IdTCPClient數據路10Indy 10 IdTCPClient使用單獨的線程讀取數據?
背景:下面的代碼是一個爲了清晰起見,我試圖去除實際數據處理部分的樣本。 Thread的思想是接收所有數據(可變長度,頭部聲明剩餘的消息長度),然後解析它(這是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;
作爲前綴,我用另一個StackOverflow的問題與印的服務器組件涉及:「Delphi 2009, Indy 10, TIdTCPServer.OnExecute, how to grab all the bytes in the InputBuffer」得到一個什麼樣我到目前爲止的基礎。
感謝您的幫助!
這是非常優雅的,但你有沒有在任何地方發佈完整的實現?我無法在您的文章中找到TMotileThreading類的完整實現。 – jamiei 2009-07-18 14:54:07