C# 整合MQTT 发布/订阅

服务端

服务端是一个控制台应用

using MQTTnet;
using MQTTnet.Core.Adapter;
using MQTTnet.Core.Diagnostics;
using MQTTnet.Core.Protocol;
using MQTTnet.Core.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestMqttServer
{
    
    
    class Program
    {
    
    
        private static MqttServer mqttServer = null;
        

        static void Main(string[] args)
        {
    
    
            MqttNetTrace.TraceMessagePublished += MqttNetTrace_TraceMessagePublished;
            new Thread(StartMqttServer).Start();

            while (true)
            {
    
    
                var inputString = Console.ReadLine().ToLower().Trim();
                if (inputString == "exit" || inputString == "q")
                {
    
    
                    mqttServer?.StopAsync();
                    Console.WriteLine("MQTT服务已停止");
                    break;
                }
                else if (inputString == "clients" || inputString == "c")
                {
    
    
                    foreach (var item in mqttServer.GetConnectedClients())
                    {
    
    
                        Console.WriteLine($"客户端标识:{item.ClientId},协议版本:{item.ProtocolVersion}");
                    }
                }
                else
                {
    
    
                    Console.WriteLine($"命令[{inputString}]无效");
                }
            }
        }

        private static void StartMqttServer()
        {
    
    
            if (mqttServer == null)
            {
    
    
                try
                {
    
    
                    var option = new MqttServerOptions
                    {
    
    
                        ConnectionValidator = p =>
                        {
    
    
                            if (p.ClientId == "c001")
                            {
    
    
                                if (p.Username != "u001" || p.Password != "p001")
                                {
    
    
                                    return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                                }
                            }
                            return MqttConnectReturnCode.ConnectionAccepted;
                        }
                    };
                    mqttServer = new MqttServerFactory().CreateMqttServer(option) as MqttServer;
                    mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived;
                    mqttServer.ClientConnected += MqttServer_ClientConnected;
                    mqttServer.ClientDisconnected += MqttServer_ClientDisconnected;
                }
                catch(Exception e)
                {
    
    
                    Console.WriteLine(e.Message);
                    return;
                }
            }
            mqttServer.StartAsync();
            Console.WriteLine("MQTT服务器启动成功");
        }

        private static void MqttServer_ClientDisconnected(object sender, MqttClientDisconnectedEventArgs e)
        {
    
    
            Console.WriteLine($"客户端[{e.Client.ClientId}]断开连接");
        }

        private static void MqttServer_ClientConnected(object sender, MqttClientConnectedEventArgs e)
        {
    
    
            Console.WriteLine($"客户端[{e.Client.ClientId}]已连接,协议版本:{e.Client.ProtocolVersion}");
        }

        private static void MqttServer_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
        {
    
    
            Console.WriteLine($"客户端[{e.ClientId}]>> 主题:{e.ApplicationMessage.Topic} 负荷:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} QoS:{e.ApplicationMessage.QualityOfServiceLevel} 保留:{e.ApplicationMessage.Retain}");
        }

        private static void MqttNetTrace_TraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
        {
    
    
            
        }
    }
}


客户端

在这里插入图片描述

using MQTTnet;
using MQTTnet.Core;
using MQTTnet.Core.Client;
using MQTTnet.Core.Packets;
using MQTTnet.Core.Protocol;
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 TestMqttClient
{
    
    
    public partial class FmMqttClient : Form
    {
    
    
        private MqttClient mqttClient = null;

        public FmMqttClient()
        {
    
    
            InitializeComponent();
            Task.Run(async () => {
    
     await ConnectionMqttServerAsync(); });
        }

        private async Task ConnectionMqttServerAsync()
        {
    
    
            if (mqttClient == null)
            {
    
    
                mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
                mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                mqttClient.Connected += MqttClient_Connected;
                mqttClient.Disconnected += MqttClient_Disconnected;
            }
            try
            {
    
    
                var options = new MqttClientTcpOptions
                {
    
    
                    Server = "192.168.1.88",
                    ClientId = Guid.NewGuid().ToString().Substring(0, 5),
                    UserName = "u001",
                    Password = "p001",
                    CleanSession = true
                };
                await mqttClient.ConnectAsync(options);
            }
            catch (Exception e)
            {
    
    
                Invoke((new Action(() =>
                {
    
    
                    txtReceiveMessage.AppendText($"连接到MQTT服务器失败" + Environment.NewLine + e.Message + Environment.NewLine);
                })));
            }
        }

        private void MqttClient_Disconnected(object sender, EventArgs e)
        {
    
    
            Invoke((new Action(() =>
            {
    
    
                txtReceiveMessage.AppendText("已断开MQTT服务器" + Environment.NewLine);
            })));
        }

        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_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.SubscribeAsync(new List<TopicFilter> {
    
    
                new TopicFilter(topic,MqttQualityOfServiceLevel.AtMostOnce)
            });

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

        private void BtnPublish_Click(object sender, EventArgs e)
        {
    
    
            string topic = txtPubTopic.Text.Trim();
            if (string.IsNullOrEmpty(topic))
            {
    
    
                MessageBox.Show("发布主题不能为空");
                return;
            }
            string inputString = txtSendMessage.Text.Trim();
            var appMsg = new MqttApplicationMessage(topic,Encoding.UTF8.GetBytes(inputString),MqttQualityOfServiceLevel.AtMostOnce,false);
            mqttClient.PublishAsync(appMsg);
        }
    }
}

测试

服务端

在这里插入图片描述

客户端

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41841482/article/details/114441493
今日推荐