I am using TIdTCPServer
. I have a client that has disconnected abnormally.
I am trying to disconnect this client like the following:
//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;
Sometimes the client gets disconnected from the server, and sometimes it gets stuck until the server is restarted.
What am I doing wrong? I just want to disconnect the client from the context.
here is the server onexecute event
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;
.......
........
idtodiscnnect
come from? The rest (except that exception eating and no exit from loop when you find the right client) seems to be fine.idtodiconnect
is a const parameter that sent from the client side to the server .OnExecute
handler look like? How it is coded has a big impact on howTIdTCPServer
processes disconnects. And the code shown in this question is not the safest way to disconnect a client anyway. Best to handle that in theOnExecute
event instead. Use timeouts, or flag theTClientConnection
and haveOnExecute
look for that flag, soDisconnect()
can be called in the thread that owns the client connection.