TIdTcpClient线程在一段时间后停止响应

时间:2018-10-31 21:35:27

标签: delphi indy

一段时间后,我的客户端线程停止从TIdTcpServer接收/发送命令。 这是我从雷米(Remy)的示例复制来的客户端线程:

在本地测试并且不会发生,仅在运行的环境中会发生错误...

type
  TDataEvent = procedure(const LBuffer: TIdBytes) of object;

  TReadingThread = class(TThread)
  private
    FClient : TIdTCPClient;
    FData   : TIdBytes;
    FOnData : TDataEvent;
    procedure DataReceived;
  protected
    procedure Execute; override;
  public
    constructor Create(AClient: TIdTCPClient); reintroduce;
    property OnData: TDataEvent read FOnData write FOnData;
  end;

constructor TReadingThread.Create(AClient: TIdTCPClient);
begin
  inherited Create(True);
  FClient := AClient;
end;

procedure TReadingThread.Execute;
begin
  while not Terminated do
  begin
    Form1.Cliente.IOHandler.ReadBytes(FData, szProtocol, False);

    if (FData <> nil) and Assigned(FOnData) then Synchronize(DataReceived);
  end;
end;

procedure TReadingThread.DataReceived;
begin
  if Assigned(FOnData) then FOnData(FData);
end;

procedure TForm1.DataReceived(const LBuffer: TIdBytes);
type
  PTBytes   = ^TBytes;
  PTIdBytes = ^TIdBytes;
var
  LDataSize   : Integer;
  LProtocol   : TProtocol;

  LBuffer2    : TBytes;
  LProtocol2  : TProtocol;
begin
  LProtocol := BytesToProtocol(PTBytes(@LBuffer)^);

  case LProtocol.Command of
    cmdHWID:
    begin
      HWID := LProtocol.Sender.HWID;
     end;

    cmdPing:
    begin
      InitProtocol(LProtocol2);
      LProtocol2.Command      := cmdPing;
      LProtocol2.Sender.PBack := GetTickCount;
      LBuffer2                := ProtocolToBytes(LProtocol2);
      Form1.Cliente.IOHandler.Write(PTIdBytes(@LBuffer2)^);
      ClearBuffer(LBuffer2);
    end;
  end;
end;

有一段时间,所有功能都运行良好,但是一段时间后,客户端停止接收/发送。与服务器的连接似乎仍处于打开状态。

通过ip查找连接的功能:

list := IdTCPServer1.Contexts.LockList;
      try
        for i := 0 to list.Count - 1 do
        begin
          ctx := TIdContext(list[i]);
          if ctx.Binding.PeerIP = Edit9.Text then
          begin
            TLog.AddMsg('IP FOUND');

            Achou := True;
            Cliente := TClientContext(ctx);

            SerialCn  := Cliente.Client.HWID;
            IpCn      := Cliente.Client.IP;

            break;
          end;
        end;
      finally
        IdTCPServer1.Contexts.UnlockList;
      end;

0 个答案:

没有答案