How do I have my socket reconnect by itself when the connection is lost? Preferably reusing the same connection.
How do I have my socket reconnect by itself when the connection is lost? Preferably reusing the same connection.
Keep the code that creates the connection within an infinite while(true){ Código aqui }
loop as soon as you detect that the socket has dropped, enter a continue
statement causing the code to return to the beginning of the loop, restarting the connection. When you actually want to stop and close the connection, enter a break
statement to exit the loop and arrive at the <
Since you did not enter the code you are using, I'll give you a fictitious example below:
public void InfiniteSocket(String host, Int32 port) {
var ipe = new IPEndPoint(host, port);
var soc = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
while(true) {
try {
soc.Connect(ipe);
if(!soc.Connected) //se não conectar, tenta novamente
continue;
}
catch(Exception e) {
//Algo deu errado com o endereço/porta
break; //aborta o loop
}
//Boolean ConversaComSocket(Socket socket)
//A função ConversaComSocket retorna true caso tudo tenha ocorrido bem (pode encerrar o socket) ou false caso tenha detectado que a conexão caiu!
var podeFinalizar = ConversaComSocket(soc);
if(!podeFinalizar)
continue; //volta ao inicio do loop e reabre conexão
soc.Shutdown(SocketShutdown.Both);
soc.Close();
break; //sai do loop
}
}