0
votes

I'm creating an instance of TServerSocket inside a class that is inherited from TThread. My question is, what code should be inside the Execute procedure which is the MAIN thread code ?

TServerThread = class(TThread)
private
  FServerSocket: TServerSocket;

  // FServerSocket event handlers
  procedure ClientConnect(Sender: TObject; Socket: TCustomWinSocket);
  procedure ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket);
  procedure ClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
  procedure ClientRead(Sender: TObject; Socket: TCustomWinSocket);
  procedure Listen(Sender: TObject; Socket: TCustomWinSocket);
protected
  procedure Execute; override;
public
  constructor Create;
  destructor Destroy; override;
end;

that's how the the class looks like, so you'll get the idea of how its implementation would look like.

the reason i'm asking this, is because all of the main code is happening in the event handlers, i can't think of any busy work operation that the MAIN procedure (Execute) should do, except loop and sleep ?

in here, someone suggested a message loop, but i don't think the thread will recv any messages.

1

1 Answers

4
votes

TServerSocket in non-blocking mode uses a hidden window to process window messages for socket activity, so the thread's Execute() method needs to have an active message loop to dispatch those messages, eg:

procedure TMyThread.Execute;
var
  Msg: TMsg;
begin
  ...
  ServerSocket.Active := True;
  try
    while not Terminated do
    begin
      if GetMessage(Msg, 0, 0, 0) > 0 then
      begin
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end else begin
        Break;
      end;
      ...
    end;
  finally
    ServerSocket.Active := False;
  end;
  ...
end;

procedure TMyThread.Stop;
begin
  PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
end;