Auto reconnect reusing an async socket connection

Asked

Viewed 177 times

2

How do I get my socket to reconnect itself when the connection is lost? Preferably reusing the same connection.

1 answer

0


Keep the code that creates the connection within an infinite loop while(true){ Código aqui }As soon as you detect that the socket has dropped, insert an instruction continue causing the code to return to the beginning of the loop by restarting the connection. When you really want to stop and close the connection, enter an instruction break to exit the loop and reach the checkout codes of the method

As you did not inform the code you are using I will make a dummy 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
    }        
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.