Indy TCPClient OnDisconnect事件无法正常工作

net*_*boy 3 delphi networking indy tcpclient

type
  TForm8 = class(TForm)
    idtcpclnt1: TIdTCPClient;
    idtcpsrvr1: TIdTCPServer;
    procedure FormCreate(Sender: TObject);
    procedure idtcpsrvr1Execute(AContext: TIdContext);
    procedure idtcpclnt1Disconnected(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form8: TForm8;

implementation

{$R *.dfm}

procedure TForm8.FormCreate(Sender: TObject);
begin
  idtcpclnt1.Connect;
end;

procedure TForm8.idtcpsrvr1Execute(AContext: TIdContext);
begin
  AContext.Connection.Disconnect(true); //this gets called
end;

procedure TForm8.idtcpclnt1Disconnected(Sender: TObject);
begin
  ShowMessage('true'); //but this does not
end;
Run Code Online (Sandbox Code Playgroud)

OnDC永远不会得到处理.为什么?

Rem*_*eau 11

Indy客户端组件不是事件驱动的(有一些例外,例如TIdTelnet).TIdTCPClient.OnDisconnect当服务器在其结束时断开时,不会触发该事件,就像您假设的那样.这是设计的. TIdTCPClient在尝试再次访问套接字之前,它不会知道断开连接,此时它会引发异常,例如EIdConnClosedGracefully.TIdTCPClient.OnDisconnect只有TIdTCPClient.Disconnect()在客户端调用方法时才会触发该事件,而您没有这样做.

为了检测服务器端断开连接TIdTCPClient,您必须定期读取套接字,例如在计时器或单独的线程中.