You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi 10.4中Socket Error #10054重置及线程重启方法咨询

解决Socket Error #10054后重启TIdThreadComponent线程的方法

核心问题分析

Socket Error #10054是远端重置连接或本地连接异常中断导致的,此时原线程关联的Indy套接字(如TIdTCPClient)已处于无效状态,直接重启线程会复用旧的无效资源,导致错误重复触发。

具体解决步骤

  • 彻底清理旧资源:线程停止后,必须销毁关联的TCP连接组件,不能复用。在线程的OnTerminate事件中执行资源释放:
    procedure TMainForm.gPinstamper1ThreadComponentTerminate(Sender: TObject);
    begin
      if Assigned(FTcpClient) then
      begin
        FTcpClient.Disconnect;
        FTcpClient.Free;
        FTcpClient := nil;
      end;
      gPinstamper1ThreadComponent.Active := False;
    end;
    
  • 重新初始化资源后启动线程:重启时不能直接设置Active := True,需先确保线程完全停止,再重新创建TCP组件,最后启动线程:
    procedure TMainForm.RestartTCPThread;
    begin
      // 先终止并等待线程退出
      if gPinstamper1ThreadComponent.Active then
      begin
        gPinstamper1ThreadComponent.Terminate;
        gPinstamper1ThreadComponent.WaitFor;
      end;
    
      // 重新创建TCP客户端实例
      FTcpClient := TIdTCPClient.Create(nil);
      FTcpClient.Host := '目标IP地址';
      FTcpClient.Port := 目标端口;
      FTcpClient.ReadTimeout := 3000;
    
      // 启动线程
      gPinstamper1ThreadComponent.Active := True;
    end;
    
  • 线程逻辑中增加异常捕获:在线程OnRun事件里捕获连接异常,主动终止线程触发资源清理:
    procedure TMainForm.gPinstamper1ThreadComponentRun(Sender: TIdThreadComponent);
    begin
      try
        FTcpClient.Connect;
        while not Terminated do
        begin
          // 执行TCP通信逻辑(读/写数据)
          Sleep(100);
        end;
      except
        on E: EIdSocketError do
        begin
          Terminate;
        end;
        on E: Exception do
        begin
          Terminate;
        end;
      end;
    end;
    
  • 禁止线程未终止时重启:必须调用WaitFor确保线程彻底退出后,再执行重启操作,避免资源冲突。

关键注意事项

  • TCP连接资源必须与线程生命周期绑定,线程终止时务必销毁所有关联套接字组件。
  • 连接逻辑必须放在线程内部执行,不要在主线程中处理连接,避免阻塞UI。

内容的提问来源于stack exchange,提问作者Johannes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:00:52