C# MQTT 客户端 服务端实现

废话懒得说,调用的第三方的库。NUGET下载MQTTnet即可。

这个库作者老是升级,而且版本之间老是不兼容。

UI如下C# MQTT 客户端 服务端实现_第1张图片

C# MQTT 客户端 服务端实现_第2张图片

C# MQTT 客户端 服务端实现_第3张图片 

下面是主要代码。

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

namespace MQTTClient
{
    public partial class FrmMain: Form
    {
        private MqttClient mqttClient = null;

        public FrmMain()
        {
            InitializeComponent();
        }
        /// 
        /// 客户端配置信息
        /// 
        private IMqttClientOptions Options
        {
            get
            {
                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder();
               
                builder.WithTcpServer(ConfigurationManager.AppSettings["ServerAddress"]);
                builder.WithCleanSession(false);
                builder.WithCredentials(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["UserPwd"]);
                var id=  Guid.NewGuid().ToString();
                builder.WithClientId(id);
                return builder.Build();
            }
        }
        /// 
        /// 连接到服务端
        /// 
        /// 
        private void ConnectMqttServer()
        {
            MqttFactory factory = new MqttFactory();
            if (mqttClient == null)
            {
                mqttClient = (MqttClient)factory.CreateMqttClient();
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += (s, e) =>
                {
                    if (!IsClose)
                    {
                        Invoke((new Action(() =>
                        {
                            if (txtReceiveMessage != null)
                            {
                                txtReceiveMessage.AppendText("已断开MQTT连接!" + Environment.NewLine);
                            }
                        })));
                        Invoke((new Action(() =>
                        {
                            txtReceiveMessage.AppendText("尝试重连!" + Environment.NewLine);
                        })));
                    }
                };
            }
            ConnectToServer();
        }

        private async void ConnectToServer()
        {
            try
            {

                var res = await mqttClient.ConnectAsync(Options);
            }
            catch (Exception ex)
            {
                Invoke((new Action(() =>
                {
                    txtReceiveMessage.AppendText($"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine);
                })));
            }
        }
        public bool IsClose { get; set; } = false;
        private void MqttClient_Connected(object sender, EventArgs e)
        {
            Invoke((new Action(() =>
            {
                txtReceiveMessage.AppendText("已连接到MQTT服务器!" + Environment.NewLine);
            })));
        }
        private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
            Invoke((new Action(() =>
            {
                txtReceiveMessage.AppendText($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
            })));
        }

        private void BtnSubscribe_ClickAsync(object sender, EventArgs e)
        {
            string topic = txtSubTopic.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("订阅主题不能为空!");
                return;
            }

            if (!mqttClient.IsConnected)
            {
                MessageBox.Show("MQTT客户端尚未连接!");
                return;
            }
            mqttClient.SubscribeAsync(new List {
                new TopicFilter(topic, MqttQualityOfServiceLevel.ExactlyOnce)
            });

            txtReceiveMessage.AppendText($"已订阅[{topic}]主题" + Environment.NewLine);
        }

        private async void BtnPublish_Click(object sender, EventArgs e)
        {
            string topic = txtPubTopic.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("发布主题不能为空!");
                return;
            }

            string inputString = txtSendMessage.Text.Trim();
            MqttApplicationMessageBuilder builder = new MqttApplicationMessageBuilder();
            builder.WithPayload(Encoding.UTF8.GetBytes(inputString));
            builder.WithTopic(topic);
            builder.WithRetainFlag();
            builder.WithExactlyOnceQoS();
            await mqttClient.PublishAsync(builder.Build());
        }

        private void btnDescribe_Click(object sender, EventArgs e)
        {
            string topic = txtSubTopic.Text.Trim();

            if (string.IsNullOrEmpty(topic))
            {
                MessageBox.Show("退订主题不能为空!");
                return;
            }
            if (!mqttClient.IsConnected)
            {
                MessageBox.Show("MQTT客户端尚未连接!");
                return;
            }
            mqttClient.UnsubscribeAsync(topic);
            txtReceiveMessage.AppendText($"已退订[{topic}]主题" + Environment.NewLine);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            Task.Run(async () => { ConnectMqttServer(); });
        }

        private async void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            IsClose = true;
            await   mqttClient.DisconnectAsync();
            mqttClient.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ConnectToServer();
        }
    }
}

源码地址:https://download.csdn.net/download/hotmee/12066127

执行文件:https://download.csdn.net/download/hotmee/12066103

你可能感兴趣的:(C#,WinFrom,C#)