Hi All,
Question: What I'm looking for is the most typical or best practice way to use a separate thread to receive data using an IdTCPClient in Indy 10.
Background: The below code is a sample of what I'm trying to do with the actual data processing parts removed for clarity. The Idea of the Thread is to receive all data (Variable size with a header declaring the rest of the message length) and to then to parse it (That's what the HandleData procedure does) and trigger an Event Handler depending on the command.
The TIdIOHandlerSocket is passed to the thread by the main application which also Writes data to the socket as and when it is required.
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;
As a prefix, I have used another StackOverflow question which deals with the server components of Indy: "Delphi 2009, Indy 10, TIdTCPServer.OnExecute, how to grab all the bytes in the InputBuffer" to get the basis of what I have so far.
Thanks for any help!