当前位置 : 主页 > 编程语言 > delphi >

delphi – Indy TCPClient OnDisconnect事件无法正常工作

来源:互联网 收集:自由互联 发布时间:2021-06-23
type TForm8 = class(TForm) idtcpclnt1: TIdTCPClient; idtcpsrvr1: TIdTCPServer; procedure FormCreate(Sender: TObject); procedure idtcpsrvr1Execute(AContext: TIdContext); procedure idtcpclnt1Disconnected(Sender: TObject); private { Private de
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;

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

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

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

网友评论