Skip to content

Instantly share code, notes, and snippets.

@wellington1993
Created October 29, 2024 13:54
Show Gist options
  • Save wellington1993/5ca256f8aac5e42a1c5b3ff562295975 to your computer and use it in GitHub Desktop.
Save wellington1993/5ca256f8aac5e42a1c5b3ff562295975 to your computer and use it in GitHub Desktop.
procedure TForm1.Button1Click(Sender: TObject);
var
Value: Integer;
begin
IdTCPClient1.Host := '10.1.1.27';
IdTCPClient1.Port := 7001;
IdTCPClient1.ConnectTimeout := 5000; // Timeout de conexão em milissegundos (5 segundos)
IdTCPClient1.ReadTimeout := 5000; // Timeout de leitura em milissegundos (5 segundos)
IdTCPClient1.IOHandler.Socket.UseNagle := False;
// Configurar Keep-Alive
Value := 1;
IdTCPClient1.IOHandler.Socket.SetSockOpt(Id_SOL_SOCKET, Id_SO_KEEPALIVE, PChar(@Value), SizeOf(Value));
// Tentar conectar
ConnectToServer;
end;
procedure TForm1.ConnectToServer;
begin
try
IdTCPClient1.Connect;
ShowMessage('Conexão estabelecida!');
// Inicia thread para manter a conexão ativa
TThread.CreateAnonymousThread(
procedure
begin
SendKeepAlive;
end
).Start;
except
on E: Exception do
ShowMessage('Erro ao conectar: ' + E.Message);
ReconnectInBackground;
end;
end;
procedure TForm1.Reconnect;
const
MaxRetries = 5;
var
RetryCount: Integer;
begin
RetryCount := 0;
while RetryCount < MaxRetries do
begin
Inc(RetryCount);
try
IdTCPClient1.Connect;
ShowMessage('Reconexão estabelecida!');
Exit;
except
on E: Exception do
begin
Log('Erro ao reconectar: ' + E.Message);
Sleep(1000); // Espera 1 segundo antes de tentar novamente
end;
end;
end;
ShowMessage('Falha ao reconectar após ' + IntToStr(MaxRetries) + ' tentativas.');
end;
procedure TForm1.ReconnectInBackground;
begin
TThread.CreateAnonymousThread(
procedure
begin
Reconnect;
end
).Start;
end;
procedure TForm1.SendKeepAlive;
begin
while IdTCPClient1.Connected do
begin
try
IdTCPClient1.IOHandler.Write(KeepAliveFlag);
Sleep(30000); // A cada 30 segundos
except
ReconnectInBackground;
end;
end;
end;
procedure TForm1.IdTCPClient1Disconnected(Sender: TObject);
begin
ShowMessage('Conexão perdida. Tentando reconectar...');
ReconnectInBackground;
end;
procedure TForm1.Log(const Msg: string);
begin
// Adicione aqui seu código de logging
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment