Delphi 终止来自TIdTCPServer的非活动套接字连接

Delphi 终止来自TIdTCPServer的非活动套接字连接,delphi,tcp,indy,Delphi,Tcp,Indy,我们有一个应用程序,它使用Delphi2007附带的Indy 10.1.1组件侦听传入的TCP请求 有时,我们会收到不是来自客户端应用程序的传入连接。通常情况下,会发生以下两种情况之一:1在接收到任何数据之前,客户端会终止连接,或者2接收到我们不期望的数据,然后手动终止连接 但是,我们接收到的连接没有接收到任何数据,并且在客户端从其端终止连接之前,这些连接似乎一直存在 如果在指定的时间段后没有收到数据,是否有方法终止与服务器的连接?您应该能够调用TIdTCPConnection.Disconne

我们有一个应用程序,它使用Delphi2007附带的Indy 10.1.1组件侦听传入的TCP请求

有时,我们会收到不是来自客户端应用程序的传入连接。通常情况下,会发生以下两种情况之一:1在接收到任何数据之前,客户端会终止连接,或者2接收到我们不期望的数据,然后手动终止连接

但是,我们接收到的连接没有接收到任何数据,并且在客户端从其端终止连接之前,这些连接似乎一直存在


如果在指定的时间段后没有收到数据,是否有方法终止与服务器的连接?

您应该能够调用TIdTCPConnection.Disconnect。

在OnExecute事件处理程序中,跟踪上次从客户端收到的良好数据的时间。使用连接的ReadTimeout属性,可以定期超时挂起的读取操作,以便检查客户端是否有一段时间没有发送数据,如果有,则断开连接。

将其另存为killthread.pas

unit killthread;

interface

uses
  Classes, IdTCPServer, IdTCPClient, IdContext, Types, SyncObjs;

type
  TKillThread = class(TThread)
  private
    FContext: TIdContext;
    FInterval: DWORD;
    FEvent: TEvent;
  protected
    procedure Execute; override;
  public
    constructor Create(AContext: TIdContext; AInterval: DWORD); overload;
    destructor Destroy; override;
    procedure Reset;
    procedure Stop;
  end;

implementation

{ TKillThread }

constructor TKillThread.Create(AContext: TIdContext; AInterval: DWORD);
begin
  FContext := AContext;
  FInterval := AInterval;
  FEvent := TEvent.Create(nil, False, False, '');
  inherited Create(False);
end;

destructor TKillThread.Destroy;
begin
  FEvent.Free;
  inherited Destroy;
end;

procedure TKillThread.Reset;
begin
  FEvent.SetEvent;
end;

procedure TKillThread.Stop;
begin
  Terminate;
  FEvent.SetEvent;
  WaitFor;
end;

procedure TKillThread.Execute;
begin
  while not Terminated do
  begin
    if FEvent.WaitFor(FInterval) = wrTimeout then
    begin
      FContext.Connection.Disconnect;
      Exit;
    end;
  end;
end;

end.
然后在服务器端执行以下操作:

procedure TYourTCPServer.OnConnect(AContext: TIdContext);
begin
  AContext.Data := TKillThread.Create(AContext, 120000);
end;

procedure TYourTCPServer.OnDisconnect(AContext: TIdContext);
begin
  TKillThread(AContext.Data).Stop;
end;

procedure TYourTCPServer.OnExecute(AContext: TIdContext);
begin
  if AContext.Connection.Connected then
  begin
    TKillThread(AContext.Data).Reset;
    // your code here
  end;
end;

我也有类似的问题,我用了delphi7+Indy9

我的解决方案是: 在TIdTCPServer事件onConnect中,我确实喜欢这样

procedure Tf_main.ServerHostConnect(AThread: TIdPeerThread);
begin
  //code something

  //mean AThread will do Disconnected  if Client no activity ( send receive ) on interval...) 
  AThread.Connection.ReadTimeout := 300000;  //5 minutes..

  //code something
end;

也许在Indy10你可以做类似的事情

这正是我想要的。我知道客户端有ReadTimeout属性,但我不知道连接的IOHandler有。谢谢。如果服务器连接了很多客户端,那就有点过头了,因为你正在使用的运行线程和内核对象的数量增加了一倍。