【语言-c#】MQTT 订阅与发布

一、框架

windows 10

.NETFramework 4.6.1

MQTTnet 3.0.5.0

1、packages.config



  
  
  
  
  
  
  
  
  
  

原始文档

NuGet包

二、工具

org.eclipse.paho.ui.app-1.0.2-win32.win32.x86_64.zip(jdk-8u211-windows-x64.exe)

遇到问题

Paho
A Java Runtime Environment(JRE)or Java Development Kit (JDK) 
must be available in order to run Paho. No Java virtual machine 
was found after searching the following location:
...\org.eclipse.paho.ui.app-1.0.2-win32.win32.x86_64\jre\bin\javaw.exe
Javaw.exe in your current Path

解决方案

安装 JDK 并设置环境变量 , 如:Windows 10 x64 安装 "jdk-8u211-windows-x64.exe"

jdk-8u211-windows-x64.exe 配置

JDK 安装路径举例如下,以实际安装为准:
InstallPath JDK : C:\Program Files\Java\jdk1.8.0_211
InstallPath JRE : C:\Program Files\Java\jre1.8.0_211

[电脑-属性-高级系统设置-环境变量-系统变量]
1、添加
变量名:JAVA_HOME
变量值:C:\Program Files\Java\jdk1.8.0_211
2、添加
变量名:JRE_HOME
变量值:C:\Program Files\Java\jre1.8.0_211
3、添加
变量名:CLASSPATH
变量值:.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;
4、追加
变量名:Path
变量值:;%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;

 

三、管理 NuGet 程序包 

方法一、VS2013>工具>NuGet包管理器>程序包管理器控制台

NETStandard.Library

Install-Package NETStandard.Library –Version 2.0.3

【语言-c#】MQTT 订阅与发布_第1张图片

MQTTnet

Install-Package MQTTnet –Version 3.0.5

【语言-c#】MQTT 订阅与发布_第2张图片

方法二、VS2013>解决方案资源管理器>[Project]>引用(右键)>管理NuGet程序包(N)...

NETStandard.Library

【语言-c#】MQTT 订阅与发布_第3张图片

MQTTnet

【语言-c#】MQTT 订阅与发布_第4张图片

四、编写订阅和发布代码

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

namespace CSDN
{
    class HOSMQTT
    {
        private static MqttClient mqttClient = null;
        private static IMqttClientOptions options = null;
        private static bool runState = false;
        private static bool running = false;

        /// 
        /// 服务器IP
        /// 
        private static string ServerUrl = "182.61.51.85";
        /// 
        /// 服务器端口
        /// 
        private static int Port = 61613;
        /// 
        /// 选项 - 开启登录 - 密码
        /// 
        private static string Password = "ruichi8888";
        /// 
        /// 选项 - 开启登录 - 用户名
        /// 
        private static string UserId = "admin";
        /// 
        /// 主题
        /// China/Hunan/Yiyang/Nanxian
        /// Hotel/Room01/Tv
        /// Hospital/Dept01/Room001/Bed001
        /// Hospital/#
        /// 
        private static string Topic = "China/Hunan/Yiyang/Nanxian";
        /// 
        /// 保留
        /// 
        private static bool Retained = false;
        /// 
        /// 服务质量
        /// 0 - 至多一次
        /// 1 - 至少一次
        /// 2 - 刚好一次
        /// 
        private static int QualityOfServiceLevel = 0;
        public static void Stop()
        {
            runState = false;
        }

        public static bool IsRun()
        {
            return (runState && running);
        }
        /// 
        /// 启动客户端
        /// 
        public static void Start()
        {
            try
            {
                runState = true;
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(Work));
                thread.Start();
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
            }
        }
        /// 
        /// 
        /// 
        private static void Work()
        {
            running = true;
            Console.WriteLine("Work >>Begin");
            try
            {
                var factory = new MqttFactory();
                mqttClient = factory.CreateMqttClient() as MqttClient;

                options = new MqttClientOptionsBuilder()
                    .WithTcpServer(ServerUrl, Port)
                    .WithCredentials(UserId, Password)
                    .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))
                    .Build();

                mqttClient.ConnectAsync(options);
                mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(new Func(Connected));
                mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(new Func(Disconnected));
                mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(new Action(MqttApplicationMessageReceived));
                while (runState)
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp);
            }
            Console.WriteLine("Work >>End");
            running = false;
            runState = false;
        }

        public static void StartMain()
        {
            try
            {
                var factory = new MqttFactory();

                var mqttClient = factory.CreateMqttClient();

                var options = new MqttClientOptionsBuilder()
                    .WithTcpServer(ServerUrl, Port)
                    .WithCredentials(UserId, Password)
                    .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))
                    .Build();

                mqttClient.ConnectAsync(options);

                mqttClient.UseConnectedHandler(async e =>
                {
                    Console.WriteLine("Connected >>Success");
                    // Subscribe to a topic
                    var topicFilterBulder = new TopicFilterBuilder().WithTopic(Topic).Build();
                    await mqttClient.SubscribeAsync(topicFilterBulder);
                    Console.WriteLine("Subscribe >>" + Topic);
                });

                mqttClient.UseDisconnectedHandler(async e =>
                {
                    Console.WriteLine("Disconnected >>Disconnected Server");
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        await mqttClient.ConnectAsync(options);
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine("Disconnected >>Exception" + exp.Message);
                    }
                });

                mqttClient.UseApplicationMessageReceivedHandler(e =>
                {
                    Console.WriteLine("MessageReceived >>" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                });
                Console.WriteLine(mqttClient.IsConnected.ToString());
            }
            catch (Exception exp)
            {
                Console.WriteLine("MessageReceived >>" + exp.Message);
            }
        }
        /// 
        /// 发布
        /// 
        /// 0 - 最多一次
        /// 1 - 至少一次
        /// 2 - 仅一次
        /// 
        /// 发布主题
        /// 发布内容
        /// 
        public static void Publish( string Topic,string Message)
        {
            try
            {
                if (mqttClient == null) return;
                if (mqttClient.IsConnected == false)
                    mqttClient.ConnectAsync(options);

                if (mqttClient.IsConnected == false)
                {
                    Console.WriteLine("Publish >>Connected Failed! ");
                    return;
                }
                
                Console.WriteLine("Publish >>Topic: " + Topic + "; QoS: " + QualityOfServiceLevel + "; Retained: " + Retained + ";");
                Console.WriteLine("Publish >>Message: " + Message);
                MqttApplicationMessageBuilder mamb = new MqttApplicationMessageBuilder()
                 .WithTopic(Topic)
                 .WithPayload(Message).WithRetainFlag(Retained);
                if (QualityOfServiceLevel == 0)
                {
                    mamb = mamb.WithAtMostOnceQoS();
                }
                else if (QualityOfServiceLevel == 1)
                {
                    mamb = mamb.WithAtLeastOnceQoS();
                }
                else if (QualityOfServiceLevel == 2)
                {
                    mamb = mamb.WithExactlyOnceQoS();
                }

                mqttClient.PublishAsync(mamb.Build());
            }
            catch (Exception exp)
            {
                Console.WriteLine("Publish >>" + exp.Message);
            }
        }
        /// 
        /// 连接服务器并按标题订阅内容
        /// 
        /// 
        /// 
        private static async Task Connected(MqttClientConnectedEventArgs e)
        {
            try
            {
                List listTopic = new List();
                if (listTopic.Count() <= 0)
                {
                    var topicFilterBulder = new TopicFilterBuilder().WithTopic(Topic).Build();
                    listTopic.Add(topicFilterBulder);
                    Console.WriteLine("Connected >>Subscribe " + Topic);
                }
                await mqttClient.SubscribeAsync(listTopic.ToArray());
                Console.WriteLine("Connected >>Subscribe Success");
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
        /// 
        /// 失去连接触发事件
        /// 
        /// 
        /// 
        private static async Task Disconnected(MqttClientDisconnectedEventArgs e)
        {
            try
            {
                Console.WriteLine("Disconnected >>Disconnected Server");
                await Task.Delay(TimeSpan.FromSeconds(5));
                try
                {
                    await mqttClient.ConnectAsync(options);
                }
                catch (Exception exp)
                {
                    Console.WriteLine("Disconnected >>Exception " + exp.Message);
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
        /// 
        /// 接收消息触发事件
        /// 
        /// 
        private static void MqttApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                string text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                string Topic = e.ApplicationMessage.Topic;
                string QoS = e.ApplicationMessage.QualityOfServiceLevel.ToString();
                string Retained = e.ApplicationMessage.Retain.ToString();
                Console.WriteLine("MessageReceived >>Topic:" + Topic + "; QoS: " + QoS + "; Retained: " + Retained + ";");
                Console.WriteLine("MessageReceived >>Msg: " + text);
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
    }
}

五、测试

1、启动

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSDN
{
    class Program
    {
        static void Main(string[] args)
        {
            HOSMQTT.Start();
        }
    }
}

2、使用Paho 工具发布消息

设置服务器IP和端口

【语言-c#】MQTT 订阅与发布_第5张图片

设置用户名密码

【语言-c#】MQTT 订阅与发布_第6张图片

连接服务

【语言-c#】MQTT 订阅与发布_第7张图片

发布消息

【语言-c#】MQTT 订阅与发布_第8张图片

监控订阅结果

【语言-c#】MQTT 订阅与发布_第9张图片

 

 

 

你可能感兴趣的:(语言-CSharp)