使用MQTTnet(Version=4.3.1.873)库实现多客户端连接多服务端,同时实现断线重连;
如下图所示,开启3个客户端连接3个服务端,当其一个服务端出现异常(服务停止,网络异常无法连接)导致连接断开时,实现每5秒连接一次
MQTT连接服务核心类:业务需求是一个客户端对应的一个MQTT服务,因此按照服务端个数创建对应的客户端连接,实现通过每一个服务端订阅消息,获取数据
using MQTTnet.Client;
using MQTTnet.Diagnostics;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MqttConnectManage
{
public class MqttClientManage
{
public readonly List<IMqttClient> _clients = new List<IMqttClient>();
public readonly string[] _serverAdr;
private List<MqttClientOptions> serverOptions = new List<MqttClientOptions>();
private readonly IMqttNetLogger logger;
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// 日志记录
/// </summary>
/// <param name="logger"></param>
public MqttClientManage(IMqttNetLogger logger)
{
this.logger = logger;
}
/// <summary>
/// 客户端连接信息
/// </summary>
/// <param name="brokerAddress"></param>
/// <param name="port"></param>
/// <param name="clientId"></param>
/// <param name="username"></param>
/// <param name="password"></param&