MqttNet 通訊


MQTT,IBM發明的物聯網通訊協議基於tcp ip , 收集傳感器上的數據。

下圖理解:  broker 這里有很多消息,根據主題不同來進行區分,它這里可以保管所有連過來的客戶端的數據,然后客戶端,通過訂閱broker它有的主題進行獲取數據。

學習網址:https://github.com/chkr1011/MQTTnet/wiki/Client

broker網址 代理:http://www.mqtt-dashboard.com/   

 

 

開發(只需客戶端):

vs2015

1.添加引用本文MQTTnet2.8.4(管理NuGet程序包)

2.界面

3.代碼

using MQTTnet;
using MQTTnet.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static IMqttClient mqttClient = null;
        public static IMqttClientOptions options = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            //實例化對象
            var factory = new MqttFactory();
            mqttClient = factory.CreateMqttClient();
            mqttClient.Connected += SubscribeTopic;
            mqttClient.Disconnected += MqttClient_Disconnected;
            mqttClient.ApplicationMessageReceived += Receive;
            //配置參數
            //options = new MqttClientOptionsBuilder()
            //    .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))
            //    .WithTcpServer("broker.hivemq.com")
            //    .WithCredentials("bud", "%spencer%")
            //    .WithTls()
            //    .WithCleanSession()
            //    .Build();
            options = new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").Build();
            //連接
            Task.Run(async () => { await ConnectMqtt(); });
        }
        public async Task ConnectMqtt()
        {
            try
            {
                MqttClientConnectResult x = await mqttClient.ConnectAsync(options);
            }
            catch (Exception ex)
            {
                Invoke((new Action(() =>
                {
                    textBox2.Text = $"連接到MQTT服務器失敗!" + Environment.NewLine + ex.Message + Environment.NewLine;
                })));
            }
        }
        //接收消息
        public async void Receive(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                Invoke((new Action(() =>
                {
                    //textBox2.AppendText("### RECEIVED APPLICATION MESSAGE 接收消息 ###");
                    textBox2.AppendText($"Topica(主題) = {e.ApplicationMessage.Topic}" + "\t\n");
                    textBox2.AppendText($"Payloada(內容) = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}" + "\t\n");
                    //textBox2.AppendText($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    //textBox2.AppendText($"+ Retain = {e.ApplicationMessage.Retain}");
                })));
            }
            catch (Exception ex)
            {
                Invoke((new Action(() =>
                {
                    textBox2.Text = ex.Message;
                })));
            }
        }
        //連接成功
        public async void SubscribeTopic(object sender, EventArgs e)
        {
            Invoke((new Action(() => { label2.Text = "連接成功"; })));
        }
        
        /// <summary>
        /// 連接失敗
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public async void MqttClient_Disconnected(object sender, EventArgs e)
        {
            Invoke((new Action(() =>
            {
                textBox2.AppendText("連接失敗!" + Environment.NewLine);
            })));
            //重新連接
            await Task.Delay(TimeSpan.FromSeconds(3));
            try
            {
                await mqttClient.ConnectAsync(options);
                Invoke((new Action(() =>
                {
                    textBox2.AppendText("連接成功!");
                })));
            }
            catch
            {
                Invoke((new Action(() =>
                {
                    textBox2.AppendText("連接失敗!");
                })));
            }


        }
        /// <summary>
        /// 訂閱消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string topic = textBox1.Text;
            mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build());
            textBox2.AppendText("### 訂閱" + topic + "成功 ###\t\n");
        }

        /// <summary>
        /// 釋放資源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            mqttClient.Dispose();
            textBox2.AppendText("### 斷開連接###\t\n");
        }
        /// <summary>
        /// 發布一個主題內容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            var message = new MqttApplicationMessageBuilder()
                .WithTopic(textBox3.Text)
                .WithPayload(textBox4.Text)
                .WithExactlyOnceQoS()
                .WithRetainFlag()
                .Build();
             mqttClient.PublishAsync(message);
        }
    }
}

4.運行效果

  這些數據就是根據你的主題從http://www.mqtt-dashboard.com/   代理取來,你也可以發布主題的內容,別人也可以訂閱你的主題,取數據。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM