Search code examples
delphitcpindydelphi-10.1-berlin

Delphi: TIdTCPClient disconnect don't close the connection


I'm investigation on a growing of active TCP connection.

Seems TIdTCPClient.Disconnect don't close connection.

This is a sample project

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  IdTCPClient;

var
  FClient: TIdTCPClient;
begin
  try
    FClient := TIdTCPClient.Create();
    FClient.Connect('LOCALHOST', 6379);

    FClient.Disconnect;
    FClient.Free;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Opening this console application multiple times cause a growing of the connection

netstat -na | find "6379"

enter image description here

Side note: I'm on Berlin 10, Windows 7 (but is the same on Windows 10)


Solution

  • Disconnect() is closing the connection. The TIME_WAIT state is normal TCP behavior.

    Whichever peer is first to actively close the TCP connection (in this case, your client), its socket endpoint goes into the TIME_WAIT state, which is a safety feature of TCP to discard any stray packets remaining in that connection. The endpoint will be fully released after a few moments once TIME_WAIT times out.

    On the other peer, the one passively receiving notification of the closure, its socket endpoint goes into the CLOSE_WAIT state instead, and is released once the closure is ACKed by the other peer. There is no TIME_WAIT on that side.

    See TIME_WAIT and its design implications for protocols and scalable client server systems, which goes into a very lengthy discussion of what TIME_WAIT is, why it exists, and how to work with it effectively.