Search code examples
delphitcpindygprs

Getting a lot of "Read timed out" exceptions from Indy's IdTCPServer


"Read timed out" exception is raising at ReadBytes(B1, 600, False) for 50% of the connection requests and 20% at ReadBytes(B3, 5, False). So only a few connections finish properly. I know the process for making 600 bytes at the client side doesn't take more than 2 seconds. By the way there is no improvements in the results if I increase ReadTimeout from 10000 to 20000. There are about 50 clients which usually connect at diverse day times, so we don't have a crowded server. My goal by setting ReadTimeout is to close the connection when there are some problems as soon as possible. Is there any problem with my code or should I search for the problem some where else?

procedure TForm1.IdTCPServerExecute(AContext: TIdContext);
var
  Log: TConnectionLog;
  B1, B2, B3: TIdBytes;
begin
  try
    try
      Log := TConnectionLog.Create;
      Log.ConnectDateTime := Now;
      Log.ClientIP := AContext.Binding.PeerIP;

      AContext.Connection.IOHandler.ReadTimeout := 10000; 
      AContext.Connection.IOHandler.ReadBytes(B1, 600, False);
      AContext.Connection.IOHandler.ReadTimeout := IdTimeoutDefault;
      Log.Bytes600ReceiveDateTime := Now;

      SetLength(B2, 200);
      AContext.Connection.IOHandler.Write(B2);
      Log.Bytes200SendDateTime := Now;

      AContext.Connection.IOHandler.ReadTimeout := 15000; 
      AContext.Connection.IOHandler.ReadBytes(B3, 5, False);
      AContext.Connection.IOHandler.ReadTimeout := IdTimeoutDefault;
      Log.Bytes5ReceiveDateTime := Now;
    except
      on E: Exception do
      begin
        Log.ExceptionMessage := E.Message;
        raise;
      end;
    end;
  finally
    TThread.Synchronize(nil,
      procedure
      begin
        SaveLog(Log);
      end);
    Log.Free;
  end;
end;

Delphi 10.2; Indy 10.6.2; Network type: 2G/GPRS


Solution

  • Following the guidance from Remy Lebeau, I did some network traffic monitoring for many days and found out the problem is raised from the low quality of network in which TCP segments with size of bigger than 100 bytes are getting lost most of the times!