MQTTnet.Extensions.ManagedClient
一、MQTT客户端简单暴力版
可将以下代码直接挂在物体上使用
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;
using QFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using UnityEngine;
public class UDPDataMqtt : MonoBehaviour
{
string[] topicArray;
//private IMqttClient m_mqttClient = null;
private IManagedMqttClient m_managedmqttClient;
private MqttFactory Factory = new MqttFactory();
/// <summary>
/// 操作参数
/// </summary>
private MqttClientOptions Options;
/// <summary>
/// 消息参数
/// </summary>
private ManagedMqttClientOptions ManagedOptions;
// Start is called before the first frame update
async void Start()
{
//将XML文件加载进来
XDocument document = XDocument.Load(CommonInfo.NetWorkSettingPath + "/MqttSConfig.xml");
//获取到XML的根元素进行操作
XElement root = document.Root;
XElement ele = root.Element("MqttConfig");
//获取心跳包时间间隔
XAttribute Topic = ele.Attribute("MQTTDataTopics");
if (!string.IsNullOrEmpty(Topic.Value))
{
topicArray = Topic.Value.Split(new char[] {
';' }, StringSplitOptions.RemoveEmptyEntries);
}
await ConnectMqttServerAsync();
}
/// <summary>
/// 客户端初始化
/// </summary>
public void Client_Init()
{
//配置初始化
//配置连接参数
Options = new MqttClientOptionsBuilder()
.WithTcpServer("127.0.0.1", 1883) //服务器地址端口号
.WithClientId("JiJuReceiveData") //连接客户端id
.WithCredentials("", "") //用户名账号密码 没有可不填
.WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
// .WithCleanSession()
.WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
.Build();
//配置重连机制
ManagedOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(Options)
.Build();
//创建客户端
m_managedmqttClient = Factory.CreateManagedMqttClient();
//配置数据接收事件
m_managedmqttClient.ApplicationMessageReceivedAsync += Receive_Event;
m_managedmqttClient.ConnectedAsync += Connected_Event;
m_managedmqttClient.DisconnectedAsync += Disconnected_Event;
}
public async Task ConnectMqttServerAsync()
{
Client_Init();
try
{
//订阅主题
if (topicArray.Length > 0)
{
await m_managedmqttClient.SubscribeAsync(
topicArray.Select(t => new MqttTopicFilterBuilder().WithTopic(t).WithAtLeastOnceQoS().Build()).ToArray()
);
}
//连接服务器
await m_managedmqttClient.StartAsync(ManagedOptions);
}
catch (Exception e)
{
Console.WriteLine(e);
}
#region m_mqttClient
//配置连接参数
//var options = new MqttClientOptionsBuilder()
// .WithTcpServer("127.0.0.1", 1883)
// .WithClientId(Guid.NewGuid().ToString())
// .WithCleanSession()
// .WithKeepAlivePeriod(TimeSpan.FromSeconds(5))
// .Build();
//if (m_mqttClient == null)
//{
// m_mqttClient = new MqttFactory().CreateMqttClient();
// // MqttServerOptions mqttServerOptions = new MqttServerOptions();
// // mqttServer = new MqttFactory().CreateMqttServer(mqttServerOptions);
//}
// await m_mqttClient.ConnectAsync(options);