一、MQTT客户端
代码如下(示例):
csharp
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp.Scripts
{
public class MQTTClientConnent:SingleTon<MQTTClientConnent>
{
private IMqttClient m_mqttClient = null;
private IManagedMqttClient m_managedmqttClient;
private MqttFactory Factory = new MqttFactory();
/// <summary>
/// 操作参数
/// </summary>
private MqttClientOptions Options;
/// <summary>
/// 消息参数
/// </summary>
private ManagedMqttClientOptions ManagedOptions;
private string m_UDPTitleS;
/// <summary>
/// 客户端初始化
/// </summary>
public void Client_Init()
{
m_UDPTitleS = GetConfigurationSetting.GetInstance.GetKeyValue("UDPTitle");
//配置初始化
//配置连接参数
Options = new MqttClientOptionsBuilder()
.WithTcpServer("127.0.0.1", 1883)
.WithClientId("JiJuID")
.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
{
//订阅主题
string[] topicArray = new string[] { };
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);
// await m_mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("test/topic").Build());
// 发布一条消息
//var applicationMessage = new MqttApplicationMessageBuilder()
// .WithTopic("4001")
// .WithPayload("Hello, MQTT!")
// .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
// .Build();
// await m_mqttClient.PublishAsync(applicationMessage);
#endregion
Console.WriteLine("MQTT start-----=====");
}
private async Task Disconnected_Event(MqttClientDisconnectedEventArgs arg)
{
await Task.Delay(100);
Console.WriteLine("MQTT断开链接=====" + arg.ToString());
}
private async Task Receive_Event(MqttApplicationMessageReceivedEventArgs arg)
{
await Task.Delay(100);
}
private async Task Connected_Event(MqttClientConnectedEventArgs arg)
{
await Connected_Func(arg);
}
/// <summary>
/// 连接服务器处理方法
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public virtual async Task Connected_Func(MqttClientConnectedEventArgs arg)
{
await Task.Delay(100);
Console.WriteLine("MQTT连接成功====="+ arg.ToString());
}
// MqttServer mqttServer;
/// <summary>
/// 客户端断开
/// </summary>
public void Disconnected()
{
m_managedmqttClient.StopAsync();
// m_managedmqttClient.ApplicationMessageReceivedAsync -= Receive_Event;
m_managedmqttClient.ConnectedAsync -= Connected_Event;
m_managedmqttClient.DisconnectedAsync -= Disconnected_Event;
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="topic">主题</param>
/// <param name="content">内容</param>
public virtual void SendMessage(string topic, string content)
{
if (m_managedmqttClient != null && m_managedmqttClient.IsConnected)
m_managedmqttClient.EnqueueAsync(m_UDPTitleS + topic, content);
// Console.WriteLine("MQTTSend=====" + m_UDPTitleS + topic + "__" + content);
}
}
}