官方示例:
https://github.com/dotnet/MQTTnet/tree/master/Samples
客户端:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Implementations;
using MQTTnet.Server;
using OneLink.Code.Config;
using OneLink.Code.Model.Throw;
using OneLink.Com.Public.Enum;
namespace OneLink.Com.Service.MqttService
{
/// <summary>
/// Mqtt客户端后台任务(自动统一注入)
/// </summary>
public class MqttClientService : IHostedService
{
public static IMqttClient _mqttClient;
public MqttClientService(
)
{
}
/// <summary>
/// 程序启动时调用
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task StartAsync(CancellationToken cancellationToken)
{
MqttClientTask();
}
/// <summary>
/// 托管关闭时调用
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task StopAsync(CancellationToken cancellationToken)
{
}
/// <summary>
/// mqtt任务
/// </summary>
public void MqttClientTask()
{
if (GlobalConfig.GlobalMqttServiceConfig == null)
{
throw ApiExceptionBase.Fail(((int)ErrorCodeType.请配置Mqtt).ToString(), ErrorCodeType.请配置Mqtt.ToString());
}
_ = Task.Run(async () =>
{
Thread.Sleep(1000);
try
{
var mqttFactory = new MqttFactory();
//使用Build构建
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer(GlobalConfig.GlobalMqttServiceConfig.Ip, GlobalConfig.GlobalMqttServiceConfig.Port)
.WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
.WithClientId("localhost_" + Guid.NewGuid())
.WithCleanSession(false)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(30))
.WithCredentials(GlobalConfig.GlobalMqttServiceConfig.User, GlobalConfig.GlobalMqttServiceConfig.Pwd)
.Build();
_mqttClient = mqttFactory.CreateMqttClient();
//与3.1对比,事件订阅名称和接口已经变化
_mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
_mqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
_mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
await _mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
}
catch (Exception ex)
{
Console.WriteLine($"Mqtt客户端尝试连接出错:{ex.Message}");
}
});
}
private Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
//主题
var topic = arg.ApplicationMessage.Topic;
//消息
var msg = System.Text.Encoding.Default.GetString(arg.ApplicationMessage.Payload);
Console.WriteLine("接收消息:" + topic);
//推送消息
_mqttClient.PublishStringAsync("/2345", "1231311");
return Task.CompletedTask;
}
private async Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
{
Console.WriteLine($"Mqtt客户端连接成功.");
var mqttFactory = new MqttFactory();
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(f => { f.WithTopic("/mqttnet/samples/topic/1"); })
.Build();
var response = await _mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
Console.WriteLine("订阅消息");
}
private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
{
Console.WriteLine($"Mqtt客户端连接断开");
//重连
MqttClientTask();
return Task.CompletedTask;
}
}
}