MQTTnet.Extensions.ManagedClient客户端连接

一、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);
        }

    }
}

相关推荐
逐·風40 分钟前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
_oP_i2 小时前
Unity Addressables 系统处理 WebGL 打包本地资源的一种高效方式
unity·游戏引擎·webgl
m0_656974744 小时前
C#中的集合类及其使用
开发语言·c#
九鼎科技-Leo4 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo6 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net
.net开发6 小时前
WPF怎么通过RestSharp向后端发请求
前端·c#·.net·wpf
小乖兽技术6 小时前
C#与C++交互开发系列(二十):跨进程通信之共享内存(Shared Memory)
c++·c#·交互·ipc
幼儿园园霸柒柒7 小时前
第七章: 7.3求一个3*3的整型矩阵对角线元素之和
c语言·c++·算法·矩阵·c#·1024程序员节
平凡シンプル9 小时前
C# EF 使用
c#
丁德双10 小时前
winform 加载 office excel 插入QRCode图片如何设定位置
c#·excel