How to track number of clients with Indy TIdTCPServer

Roddy picture Roddy · Apr 1, 2011 · Viewed 11.7k times · Source

I want to know the number of current client connections to an Indy 9 TIdTCPServer (on Delphi 2007)

I can't seem to find a property that gives this.

I've tried incrementing/decrementing a counter on the server OnConnect/OnDisconnect events, but the number never seems to decrement when a client disconnects.

Any suggestions?

Answer

Remy Lebeau picture Remy Lebeau · Apr 2, 2011

The currently active clients are stored in the server's Threads property, which is a TThreadList. Simply lock the list, read its Count property, and then unlock the list:

procedure TForm1.Button1Click(Sender: TObject);
var
  NumClients: Integer;
begin
  with IdTCPServer1.Threads.LockList do try
    NumClients := Count;
  finally
    IdTCPServer1.Threads.UnlockList;
  end;
  ShowMessage('There are currently ' + IntToStr(NumClients) + ' client(s) connected');
end;

In Indy 10, the Threads property was replaced with the Contexts property:

procedure TForm1.Button1Click(Sender: TObject);
var
  NumClients: Integer;
begin
  with IdTCPServer1.Contexts.LockList do try
    NumClients := Count;
  finally
    IdTCPServer1.Contexts.UnlockList;
  end;
  ShowMessage('There are currently ' + IntToStr(NumClients) + ' client(s) connected');
end;