所谓的潇洒

导航

MQTTNetHelper

项目.NetFramework版本4.5.2

Nuget安装MQTTnet版本3.0.12

 

using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common
{
        private static MqttClient mqttClient = null;
        private static IMqttClientOptions mqttOption = null;

        public static void Subscribe()
        {
            try
            {
                mqttClient = new MqttFactory().CreateMqttClient() as MqttClient;
          //ClientId可以自定义,用于区分同账号不同客户端,多个客户端相同账号相同ClientId会导致其中只有一个能订阅到消息 mqttOption = new MqttClientOptionsBuilder().WithClientId("id1").WithTcpServer("192.168.1.101", 8000).WithCredentials("zhangsan", "abc123").WithTls().WithCleanSession().Build(); mqttClient.UseConnectedHandler(ConnectedHandler); mqttClient.UseApplicationMessageReceivedHandler(MessageReceivedHandler); mqttClient.UseDisconnectedHandler(DisconnectedHandler); mqttClient.ConnectAsync(mqttOption, CancellationToken.None); } catch (Exception ex) { //LogHelper.logger.Error(ex); } } static async Task ConnectedHandler(MqttClientConnectedEventArgs e) { try { await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").Build()); } catch (Exception ex) { //LogHelper.logger.Error(ex); } } static async Task MessageReceivedHandler(MqttApplicationMessageReceivedEventArgs e) { try { await new Task(() => { if (e.ApplicationMessage.Topic == "my/topic") { Console.WriteLine(Encoding.Default.GetString(e.ApplicationMessage.Payload));//PayLoad就是订阅到的消息的内容 } }); } catch (Exception ex) { //LogHelper.logger.Error(ex); } } static async Task DisconnectedHandler(MqttClientDisconnectedEventArgs e) { try { await mqttClient.ConnectAsync(mqttOption, CancellationToken.None);//断线重连 } catch (Exception ex) { //LogHelper.logger.Error(ex); } } }

posted on 2020-12-13 15:26  所谓的潇洒  阅读(703)  评论(0编辑  收藏  举报