TIdTCPServer完全断开客户端与服务器的连接

时间:2017-07-09 21:16:57

标签: delphi indy indy10

我正在使用TIdTCPServer。我有一个异常断开的客户端。  我试图断开此客户端,如下所示:

//class TClientConnection = class(TIdServerContext)

var
  Clienttodisconnect: TClientConnection;

List := Server.Contexts.LockList;
try
  for I := 0 to List.Count - 1 do
  begin
    Clienttodisconnect := TClientConnection(List.Items[I]);
    if Clienttodisconnect.uuid = idtodiscnnect then
    begin
      try    
        Clienttodisconnect.Connection.Disconnect;    
      except
      end;
    end;
  end;
finally
  Server.Contexts.UnlockList;
end;

有时客户端与服务器断开连接,有时它会在服务器重新启动之前卡住。

我做错了什么?我只想将客户端与上下文断开连接。

这是服务器onexecute事件

var
  Connection: TClientConnection;
  CMD: String;
  Cache, OutboundCmds: TStringList;
  I: integer;
  UConnected : Boolean;
  Len: Integer;
begin

sleep(10);

Try
UConnected := AContext.Connection.Connected;
Except
UConnected := False;
End;

If UConnected <> True Then
begin
AContext.Connection.Disconnect;
exit;
end;

Len := AContext.Connection.IOHandler.InputBuffer.Size;


If Len >= 200000 then
begin
AContext.Connection.Disconnect;
exit;

end;

Connection := AContext as TClientConnection;



  // check for pending outbound commands...
  OutboundCmds := nil;
  try
    Cache := Connection.OutboundCache.Lock;
    try
      if Cache.Count > 0 then
      begin
        OutboundCmds := TStringList.Create;
        OutboundCmds.Assign(Cache);
        Cache.Clear;
      end;
    finally
      Connection.OutboundCache.Unlock;
    end;

    if OutboundCmds <> nil then
    begin
      for I := 0 to OutboundCmds.Count - 1 do
      begin
        AContext.Connection.IOHandler.Writeln(OutboundCmds.Strings[I],
          IndyTextEncoding_UTF8);
      end;
      Connection.LastSendRecv := Ticks64;
    end;




  finally
    if OutboundCmds <> nil then
    begin
      for I := 0 to OutboundCmds.Count - 1 do
      begin
        OutboundCmds.Objects[I].Free;
      end;
    end;
    OutboundCmds.Free;
  end;

  // check for a pending inbound command...
  if AContext.Connection.IOHandler.InputBufferIsEmpty then
  begin
    AContext.Connection.IOHandler.CheckForDataOnSource(100);
    AContext.Connection.IOHandler.CheckForDisconnect;
    if AContext.Connection.IOHandler.InputBufferIsEmpty then
    begin
    if GetElapsedTicks(Connection.LastSendRecv) >= 30000 then
     AContext.Connection.Disconnect;
     Exit;
    end;
  end;

.......

........ 

1 个答案:

答案 0 :(得分:1)

我会建议更像这样的事情:

public void closestNumber(){
  int a[] = {-1, 58, 32, 16, 54};
  int current=a[0];
  int diff=Maths.abs(32-current);
  int index=0;

  for (int i=0; i<a.length; i++){
    int newDiff= Maths.abs(32-a[i]);
    if (newDiff< diff){
    index=i;
    }
    System.out.println(index);
  }
}