This is probably a stupid question, but anyway.
My application is distributed, so instead of calling a function, I create a thread. And all communication is through sockets.
Like this:
TNode = class(TThread)
protected
MyWorker: TWorker; // This is what is going to execute the action!
public
procedure Execute; override;
end;
THandler = class(TThread)
public
procedure Execute; override;
function ProcessRequest(Request, URI: string): integer;
end;
TWorker = class(TThread)
public
constructor Create(Command: string; Data: string);
procedure Execute; override;
end;
procedure TNode.Execute;
var
ClientSock:TSocket;
begin
with MySocket do
begin
CreateSocket;
SetLinger(True, 1000);
Bind('0.0.0.0', MyPort);
Listen;
repeat
if Terminated then Break;
if CanRead(1000) then
begin
ClientSock := Accept;
if LastError=0 then THandler.Create(ClientSock);
end;
until False;
end;
end;
procedure THandler.Execute;
begin
...
ResultCode := ProcessRequest(Method, URI);
MySocket.SendString(Protocol + ' ' + IntTostr(ResultCode) + CRLF);
...
end;
function THandler.ProcessRequest(Request, URI: string): integer;
begin
...
MyWorker.Create(URI, Data);
...
end;
I left out all the irrelevant details.
Anyway, in ProcessRequest I have to create the right worker. So, if I created a new one, like so:
type
TReaderWorker = class(TWorker);
how can I get that one created without making a new TNode and THandler as well?
I tried storing the type instead:
TWorkerType = class of TWorker;
and pass that to TNode and THandler, but that crashed on the first line of the constructor (and the wrong one at that, from TWorker).
And I cannot pass them to TNode, because a new one is needed for each request.
(They start, do their thing and send a message to the specified client by themselves, if requested. And then they terminate. I don't even keep the pointers.)
How should I do that?