Search code examples
delphiindy

Indy TCP Server - Handle OnDisconnect already deleted?


I have a Delphi application with a Indy TCPServer and TCPClient. I use the AContext.Bindind.Handle for the identification of each connection (wrong?).

So I have a grid which displayed the connections and I will remove the entry after disconnection:

procedure TfrmMain.serverIndyDisconnect(AContext: TIdContext);
var I:Integer;
begin
for I := 0 to gridClients.RowCount - 1 do
begin
  if gridClients.Cells[0, I] = IntToStr(AContext.Binding.Handle) then
  begin
     gridClients.Rows[I].Delete(I);
  end;
end;

WriteLogEntry('Connection closed... (' + AContext.Binding.PeerIP+')');
end;

But in the Disconnect Event, the Handle is already empty (it's ever 401xxxxx, so the last Integer number).

Ideas?


Solution

  • You do not mention which version of Delphi or Indy you are using, but the following holds for D2010 and Indy 10.x.

    I've used the "AContext.Data" property for identification of the client. I usually Create an object there and release it when the disconnect event happens.

    New OnConnect() code:

    procedure TfrmMain.serverIndyConnect(AContext: TIdContext);
    begin
      AContext.Data := TMyObject.Create(NIL);
      // Other Init code goes here, including adding the connection to the grid
    end;
    

    Modified OnDisconnect() code below:

    procedure TfrmMain.serverIndyDisconnect(AContext: TIdContext);
    var I:Integer;
    begin
      for I := 0 to gridClients.RowCount - 1 do
      begin
        if gridClients.Cells[0, I] = IntToStr(AContext.Data) then
        begin
          gridClients.Rows[I].Delete(I);
        end;
     end;
     WriteLogEntry('Connection closed... (' + AContext.Binding.PeerIP+')');
    end;