websocket-client icon indicating copy to clipboard operation
websocket-client copied to clipboard

What is the right way to reconnect on disconnection?

Open mii9000 opened this issue 4 years ago • 4 comments

        private void DisconnectHandler(DisconnectionInfo info)
        {
            _wsClient.Reconnect().GetAwaiter().GetResult();
        }

I get system timeout exception when I try to do the above

mii9000 avatar Dec 06 '20 17:12 mii9000

Hello @Ibrahim-Islam,

reconnection is built-in, you don't have to do anything.

Configure _client.ErrorReconnectTimeout = TimeSpan.FromXxx() to set reconnection timeout when server is not available or some network error occurs. Default is 1 minute. So it is going to try every 1 minute to reconnect.

Also you can disable reconnection totally and do it manually by _client.ErrorReconnectTimeout = null or _client. IsReconnectionEnabled = false.

The last possible way is to disable reconnection inside the disconnection handler.

       private void DisconnectHandler(DisconnectionInfo info)
        {
            info.CancelReconnection = true;
        }

Marfusios avatar Dec 06 '20 22:12 Marfusios

@Marfusios Thank you for your prompt reply. I think I get the hang of it now. On reconnection, I also have to authenticate with the server but when I do that I get the same Timeout exception.

private void ReconnectionHandler(ReconnectionInfo info)
        {
            var message = $"Reconnection Happened : Type = {info.Type} | IsRunning = {_wsClient.IsRunning}";
            _logger.LogInformation(message);

            _logger.LogInformation("Retrying login because of reconnection");
            LoginAsync("abc", "123").GetAwaiter().GetResult();
            _logger.LogInformation("Retry login successful");
        }

But if I remove .GetAwaiter().GetResult() part then it seems to work fine.

image

mii9000 avatar Dec 07 '20 07:12 mii9000

Yea, don't use GetResult(), or .Result or Wait(). It blocks execution and it is very prone to dead-locks.

What does the method LoginAsync() do? Sending authentication data via websockets?
It is better and safer to use method void Send() instead of Task SendInstant() (also you don't have to deal with tasks).

If it has to be async, then it is better to take approach 'fire-and-forget' - do not await it. But don't forget to wrap content of LoginAsync into try-catch block and handle exception somehow.

Marfusios avatar Dec 07 '20 10:12 Marfusios

@Marfusios Thank you very much. Your library has made my life so much easier. Another issue I am noticing that after the application has been running for a very long time, when I try to send a message it will also crash with the above message. Any idea what might be causing it?

mii9000 avatar Dec 07 '20 15:12 mii9000