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

    }
}

相关推荐
与火星的孩子对话1 小时前
Unity3D开发AI桌面精灵/宠物系列 【三】 语音识别 ASR 技术、语音转文本多平台 - 支持科大讯飞、百度等 C# 开发
人工智能·unity·c#·游戏引擎·语音识别·宠物
response_L1 小时前
国产系统统信uos和麒麟v10在线打开word给表格赋值
java·c#·word·信创·在线编辑
MasterNeverDown1 小时前
Swagger2Md:让WebAPI文档生成变得轻松高效
c#
向宇it1 小时前
【零基础入门unity游戏开发——2D篇】2D 游戏场景地形编辑器——TileMap的使用介绍
开发语言·游戏·unity·c#·编辑器·游戏引擎
闪电麦坤9510 小时前
C#:base 关键字
开发语言·c#
mingupup11 小时前
C#连接小智服务器并将音频解码播放过程记录
c#
爱吃奶酪的松鼠丶14 小时前
.net GRPC服务搭建,跨进程调用。C#应用和Python应用之间的通信。
python·c#·.net
牙膏上的小苏打233317 小时前
Unity Surround开关后导致获取主显示器分辨率错误
unity·主屏幕
勘察加熊人19 小时前
forms实现俄罗斯方块
c#
Unity大海19 小时前
诠视科技Unity SDK开发环境配置、项目设置、apk打包。
科技·unity·游戏引擎