Search code examples
c#asp.netmqttpahoreconnect

How to M2MQTT Auto Reconnect


i'm trying to use this protocol and already have 2 clients (one to publish and another to subscribe) and a broker working.

My question is i want to implement a reconnect feature in the subscribe client because the wifi signal is unstable and don't want to manually restart the client every single time, how can i accomplish this?


Solution

  • You can use the ConnectionClosed event to detect when a disconnect happens.

    I then start a task that will try to reconnect the client. Something like:

     private async Task TryReconnectAsync(CancellationToken cancellationToken)
        {
            var connected = _client.IsConnected;
            while (!connected && !cancellationToken.IsCancellationRequested)
            {
                try
                {
                    _client.Connect(_clientId);
                }
                catch
                {
                    _logger.Log(LogLevel.Warn, "No connection to...{0}",_serverIp);
                }
                connected = _client.IsConnected;
                await Task.Delay(10000, cancellationToken);
            }
        }
    

    Not perfect, but will do the job.