我使用TIdTcpServer和TIdTcpClient让客户端和服务端进行相连.当服务端登上以后,在ListBox1中添加一条记录,并对用户类TSimpleClient的各个成员赋相应的值.当客户端断开连接时,用户类释放内存空间,并将ListBox1中相应的记录删掉.但是现在的问题是连接的时候很正常,但是当用户断开连接时,有时候能够将相应的记录删掉,有时候却删不掉,不知道是怎么回事呢?用户类在断开连接的时候是否真的释放掉内存了?是什么原因导致的呢?该如何处理?请各位帮帮忙.谢谢.
type
  TSimpleClient = class(TObject)
    Name : String; //用户的ID.
    ListLink    : Integer;
    Thread      : Pointer;
end;procedure TfrmMain.tcpServerConnect(AThread: TIdPeerThread);
var
  Client : TSimpleClient;
  ClientList : TList;
begin
  Clietn := TSimpleClient.Create;
  ClientList := TList.Create;
 
  Client.Name := IntToStr(AThread.Connection.ThreadId);
  Client.ListLink := ListBox1.Items.Count;
  Client.Thread := AThread;  ListBox1.Items.Add(Client.Name);  AThread.Data := Client;  ClientList.Add(Client);
 
end;procedure TfrmMain.tcpServerDisconnect(AThread: TIdPeerThread);
var
  Client : TSimpleClient 
begin
  Client := Pointer(AThread.Data);  ClientList.Delete(Client.ListLink);  ListBox1.Items.Delete(ListBox1.Items.IndexOf(Client.Name));// 在ListBox1中删掉相应的记录  Client.Free; // 释放掉内存空间.
  AThread.Data := nil;
  
end;

解决方案 »

  1.   

    需要注意的是,意外断线的情况下Indy的tcpServerDisconnect(AThread: TIdPeerThread);
    中AThread的数据将无法访问的
    你需要
    Try
    Excpet保护异常
    并且有机制处理意外断线下的问题
      

  2.   

    那如果我在客户端的Form.OnClose事件中这样写呢?是否可以解决问题?一定要用try...except吗?procedure TfrmClient.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
      IdTcpClient1.Disconnect;
    end;
      

  3.   

    需要在
    procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
    调用AThread.Connection.CheckForGracefulDisconnect;来检测客户端是否已经断开连接