How to track number of clients with Indy TIdTCPServer

后端 未结 4 491
Happy的楠姐
Happy的楠姐 2021-01-03 07:37

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 tr

4条回答
  •  借酒劲吻你
    2021-01-03 08:13

    This should work on Indy 9, but it is pretty outdated nowadays, and maybe something is broken in your version, try to update to the latest Indy 9 available.

    I made a simple test using Indy 10, which works very well with a simple interlocked Increment/Decrement in the OnConnect/OnDisconnect event handlers. This is my code:

    //closes and opens the server, which listens at port 1025, default values for all properties
    procedure TForm2.Button1Click(Sender: TObject);
    begin
      IdTCPServer1.Active := not IdTCPServer1.Active;
      UpdateUI;
    end;
    
    procedure TForm2.FormCreate(Sender: TObject);
    begin
      UpdateUI;
    end;
    
    //Just increment the count and update the UI
    procedure TForm2.IdTCPServer1Connect(AContext: TIdContext);
    begin
      InterlockedIncrement(FClientCount);
      TThread.Synchronize(nil, UpdateUI);
    end;
    
    //Just decrement the count and update the UI
    procedure TForm2.IdTCPServer1Disconnect(AContext: TIdContext);
    begin
      InterlockedDecrement(FClientCount);
      TThread.Synchronize(nil, UpdateUI);
    end;
    
    //Simple 'X' reply to any character, A is the "command" to exit
    procedure TForm2.IdTCPServer1Execute(AContext: TIdContext);
    begin
      AContext.Connection.IOHandler.Writeln('Write anything, but A to exit');
      while AContext.Connection.IOHandler.ReadByte <> 65 do
        AContext.Connection.IOHandler.Write('X');
      AContext.Connection.IOHandler.Writeln('');
      AContext.Connection.IOHandler.Writeln('Good Bye');
      AContext.Connection.Disconnect;
    end;
    
    //Label update with server status and count of connected clients 
    procedure TForm2.UpdateUI;
    begin
      Label1.Caption := Format('Server is %s, %d clients connected', [
        IfThen(IdTCPServer1.Active, 'Open', 'Closed'), FClientCount]);
    end;
    

    then, opening a couple of clients with telnet:

    3 connected clients

    then, closing one client

    2 connected clients

    That's it.

    INDY 10 is available for Delphi 2007, my main advise is to upgrade anyway.

提交回复
热议问题