Indy TCP服务器 - 处理OnDisconnect已全部删除?

时间:2010-05-18 08:24:52

标签: delphi indy

我有一个带有Indy TCPServer和TCPClient的delphi应用程序 我使用AContext.Bindind.Handle来识别每个连接(错误?)。

所以我有一个显示连接的网格,我将在断开连接后删除该条目:

procedure TfrmMain.serverIndyDisconnect(AContext: TIdContext);
var I:Integer;
begin
for I := 0 to gridClients.RowCount - 1 do
begin
  if gridClients.Cells[0, I] = IntToStr(AContext.Binding.Handle) then
  begin
     gridClients.Rows[I].Delete(I);
  end;
end;

WriteLogEntry('Connection closed... (' + AContext.Binding.PeerIP+')');
end;

但是在断开连接事件中,句柄已经是空的(它曾经是401xxxxx,所以是最后一个整数)。

想法?

1 个答案:

答案 0 :(得分:4)

您没有提到您使用的是哪个版本的Delphi或Indy,但以下适用于D2010和Indy 10.x.

我使用“AContext.Data”属性来识别客户端。我通常在那里创建一个对象,并在断开事件发生时释放它。

新的OnConnect()代码:

procedure TfrmMain.serverIndyConnect(AContext: TIdContext);
begin
  AContext.Data := TMyObject.Create(NIL);
  // Other Init code goes here, including adding the connection to the grid
end;

修改后的OnDisconnect()代码:

procedure TfrmMain.serverIndyDisconnect(AContext: TIdContext);
var I:Integer;
begin
  for I := 0 to gridClients.RowCount - 1 do
  begin
    if gridClients.Cells[0, I] = IntToStr(AContext.Data) then
    begin
      gridClients.Rows[I].Delete(I);
    end;
 end;
 WriteLogEntry('Connection closed... (' + AContext.Binding.PeerIP+')');
end;