Viktor Anastasov
Viktor Anastasov

Reputation: 1113

How to stop TCPServer OnExecute event from infinite execution after AContext.Connection.Disconnect?

I have this TCPServerExecute event that I want to stop from executing after I manually disconnect the connection with the client :

procedure TMainForm.TCPServerExecute(AContext: TIdContext);
var
  TCPClient : TIdTCPClient;
begin
try
  TCPClient := nil;
  try
    TCPClient := TIdTCPClient.Create(nil);
    if aConditionIsMet then begin 
      AContext.Connection.IOHandler.WriteLn('Disconnected from server.');
      AContext.Connection.Disconnect;
      Exit;
    end;
  finally
    FreeAndNil(TCPClient);
  end;
except on e : Exception do
  begin
    MainForm.Log('error in Execute=' + e.Message);
  end;
end;
end;

and at client side everything's fine but on server-side I loop through TCPServerExecute infinitely. What am I doing wrong and how can I stop TCPServerExecute from executing after I type AContext.Connection.Disconnect ?

Upvotes: 4

Views: 1273

Answers (1)

mjn
mjn

Reputation: 36664

The loop continues because Indy exceptions are not handled correctly.

Either remove the exception handler, or re-raise the exception after logging:

except 
  on e : Exception do
  begin
    MainForm.Log('error in Execute=' + e.Message);
    raise;
  end;
end;

p.s. accessing the MainForm from the server thread is not thread-safe. There are many solutions to do improve this code (TThread.Queue is one of them).

Upvotes: 2

Related Questions