Delphi: TIdTCPClient disconnect don't close the connection

543 Views Asked by At

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)

2

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

The connection is closed. TIME_WAIT indicates that local endpoint (this side) has closed the connection.

Ref: https://superuser.com/questions/173535/what-are-close-wait-and-time-wait-states