MQTT服务端实现

1、准备
安装MQTTNet库
2、界面设计
在这里插入图片描述
3、程序

public ServerForm()
        {
            InitializeComponent();
            //获取本机IP
            GetHostIpList();
        }
        #region FormLoad
        private Action<string> _updateMonitorAction;
        /// <summary>
        /// 窗体加载内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServerForm_Load(object sender, EventArgs e)
        {
            try
            {
                GetHostIpList();
                this.tbMqttServerPort.Text = "8080";
                this.tbUsername.Text = "username";
                this.tbPassword.Text = "password";
                this.btMqttServerStart.Tag = 0;
                MonitorListBoxInitialize();

            }catch(Exception ex)
            {
                this.lbxMonitor.BeginInvoke(_updateMonitorAction, ex.Message);
            }
        }
        /// <summary>
        /// 获取本机IP
        /// </summary>
        private void GetHostIpList()
        {
            var Ips = Dns.GetHostAddressesAsync(Dns.GetHostName());
            List<string> ipList = new List<string>();
            foreach (var ip in Ips.Result)
            {
                switch (ip.AddressFamily)
                {
                    case AddressFamily.InterNetwork:
                        if (!ipList.Contains(ip.ToString()))
                        {
                            ipList.Add(ip.ToString());
                        }
                        break;
                    default:
                        break;
                }
            }
            if (ipList.Count > 0)
            {
                this.cbbMqttServerIp.DataSource = ipList;
                this.cbbMqttServerIp.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// monitor列表显示控制
        /// </summary>
        private void MonitorListBoxInitialize()
        {
            _updateMonitorAction = new Action<string>((s) =>
              {
                  this.lbxMonitor.Items.Add(s);
                  if (this.lbxMonitor.Items.Count > 100)
                  {
                      this.lbxMonitor.Items.RemoveAt(0);
                  }
                  var visibleItems = this.lbxMonitor.ClientRectangle.Height / this.lbxMonitor.ItemHeight;
                  this.lbxMonitor.TopIndex = this.lbxMonitor.Items.Count - visibleItems + 1;
              });
        }
        /// <summary>
        /// monitor列表清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbxMonitor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar=='c' || e.KeyChar == 'C')
            {
                if(DialogResult.Yes==MessageBox.Show("Clear the Monitor View?", "Info", MessageBoxButtons.YesNo))
                {
                    this.lbxMonitor.Items.Clear();
                }
            }
        }
        #endregion

        #region EventProcess
        private SetModel setModel = new SetModel();
        /// <summary>
        /// 开启/停止MQTT服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btMqttServerStart_Click(object sender, EventArgs e)
        {
            setModel.Ip = this.cbbMqttServerIp.SelectedItem.ToString();
            setModel.Port = Convert.ToInt32(this.tbMqttServerPort.Text);
            setModel.Username = this.tbUsername.Text;
            setModel.Password = this.tbPassword.Text;
            try
            {
                if (int.Parse(this.btMqttServerStart.Tag.ToString()) == 0)
                {
                    StartMqttServer();
                }
                else if (int.Parse(this.btMqttServerStart.Tag.ToString()) == 1)
                {
                    StopMqttServer();
                }
            }catch(Exception ex)
            {
                Console.WriteLine($"开启关闭异常{ex.Message}");
            }
        }
        private void btServerPublish_Click(object sender, EventArgs e)
        {
            try
            {
                string topic = this.tbServerPublishTopic.Text;
                if (topic.Trim() == "")
                {
                    MessageBox.Show("Topic不能为空", "消息", MessageBoxButtons.OK);
                }
                string payload = this.tbServerPublishPayload.Text;
                MqttServerPublishTopic(topic, payload);
            }
            catch(Exception ex)
            {
                Console.WriteLine($"服务器发布异常{ex.Message}");
            }
        }
        #endregion

        #region MQTT Server
        private const int SERVER_BACK_LOG = 5;
        private MqttServer mqttServer = null;

        /// <summary>
        /// Mqtt服务器启动
        /// </summary>
        private async void StartMqttServer()
        {
            try
            {
                if (mqttServer == null)
                {
                    var optionsBuilder = new MqttServerOptionsBuilder()
                        .WithDefaultEndpointBoundIPAddress(IPAddress.Parse(setModel.Ip))
                        .WithDefaultEndpointPort(setModel.Port)
                        .WithConnectionBacklog(SERVER_BACK_LOG)
                        .WithConnectionValidator(c =>
                        {
                            if (setModel.Username == null || setModel.Password == null || c.Username != setModel.Username || c.Password != setModel.Password)
                            {
                                c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                                return;
                            }
                            c.ReasonCode = MqttConnectReasonCode.Success;
                        }).WithSubscriptionInterceptor(c =>
                        {
                            c.AcceptSubscription = true;
                        }).WithApplicationMessageInterceptor(c =>
                        {
                            c.AcceptPublish = true;
                        });
                    //MqttServerOptions options = optionsBuilder.Build() as MqttServerOptions;
                    mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
                    mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(OnMqttServerStarted);
                    mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(OnMqttServerStoped);
                    mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
                    mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
                    mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedTopicHandlerDelegate(OnMqttServerClientSubscribedTopic);
                    mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(OnMqttServerClientUnSubscribedTopic);
                    mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnServerApplicationMessageReceived);
                    await mqttServer.StartAsync(optionsBuilder.Build());
                    this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT服务器启动成功");
                }
            }catch(Exception ex)
            {
                this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT服务器启动失败:{ex.Message}");
            }
        }
        /// <summary>
        /// Mqtt服务器停止
        /// </summary>
        private async void StopMqttServer()
        {
            if (mqttServer == null) return;
            try
            {
                await mqttServer?.StopAsync();
                mqttServer = null;
                this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT服务器停止成功");
            }
            catch (Exception ex)
            {
                this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT服务器停止失败:{ex.Message}");
            }
        }
        private async void MqttServerPublishTopic(string topic, string payload)
        {
            var message = new MqttApplicationMessage()
            {
                Topic = topic,
                Payload = Encoding.UTF8.GetBytes(payload)
            };
            await mqttServer.PublishAsync(message);
            this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT服务器发布成功:{topic}");
        }

        private void OnServerApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs obj)
        {
            this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"客户端[{obj.ClientId}]>> 主题:{obj.ApplicationMessage.Topic} 负荷:{Encoding.UTF8.GetString(obj.ApplicationMessage.Payload)} Qos:{obj.ApplicationMessage.QualityOfServiceLevel} 保留:{obj.ApplicationMessage.Retain}");
        }

        private void OnMqttServerClientUnSubscribedTopic(MqttServerClientUnsubscribedTopicEventArgs obj)
        {
            this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT客户端{obj.ClientId}已取消订阅主题{obj.TopicFilter}");
        }

        private void OnMqttServerClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs obj)
        {
            this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT客户端{obj.ClientId}已成功订阅主题{obj.TopicFilter}");
        }

        private void OnMqttServerClientDisconnected(MqttServerClientDisconnectedEventArgs obj)
        {
            this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT客户端{obj.ClientId}已断开");
        }

        private void OnMqttServerClientConnected(MqttServerClientConnectedEventArgs obj)
        {
            this.lbxMonitor.BeginInvoke(_updateMonitorAction, $"MQTT客户端{obj.ClientId}已连接");
        }

        private void OnMqttServerStoped(EventArgs obj)
        {
            if (!mqttServer.IsStarted)
            {
                btMqttServerStart.BeginInvoke(new Action<string,int, Color>((t,g, c) =>
                {
                    btMqttServerStart.Text = t;
                    btMqttServerStart.Tag = g;
                    btMqttServerStart.BackColor = c;
                }), "Start",0, Color.LightGray);
            }
        }

        private void OnMqttServerStarted(EventArgs obj)
        {
            if (mqttServer.IsStarted)
            {
                btMqttServerStart.BeginInvoke(new Action<string,int, Color>((t,g,c) =>
                {
                    btMqttServerStart.Text = t;
                    btMqttServerStart.Tag = g;
                    btMqttServerStart.BackColor = c;
                }),"Stop",1,Color.LightGreen);
            }
        }
        #endregion

4、实现效果
在这里插入图片描述

MQTT(Message Queuing Telemetry Transport)是一种轻量级的通信协议,常用于物联网设备间的消息传递。dotnet mqtt服务端是基于.NET平台开发的MQTT服务端实现。 dotnet mqtt服务端提供了一套易于使用的API,可以帮助开发人员构建可靠、高效的MQTT服务器。它支持MQTT协议的各种功能,比如发布(publish)和订阅(subscribe)消息、遗嘱消息(will message)、保留消息(retained message)等。 使用dotnet mqtt服务端,开发人员可以快速、轻松地搭建一个可靠的MQTT消息传递体系。它提供了多种接入方式,可以支持不同类型的客户端设备,如传感器、嵌入式设备、移动设备等。此外,它还支持多种消息传递质量(QoS)级别的选择,可以根据需求进行灵活配置。 dotnet mqtt服务端具有较高的性能和可扩展性。它可以处理大量的消息传递请求,并提供了有效的消息处理机制,保证消息的可靠性和时效性。同时,它还支持集群部署,可以通过增加服务器节点来实现水平扩展,满足大规模消息传递场景的需求。 dotnet mqtt服务端还提供了丰富的监控和管理功能,可以帮助开发人员实时监测服务器的运行状态、连接状态、消息队列长度等。此外,它还提供了管理工具,可以对连接进行授权管理、订阅管理、消息路由等操作,确保系统的安全性和稳定性。 总之,dotnet mqtt服务端是一款功能强大、易于使用的MQTT服务端实现。它能够帮助开发人员构建高效、可靠的物联网应用系统,实现设备间的即时通信和数据传递。无论是小型项目还是大规模应用场景,dotnet mqtt服务端都是一个值得推荐的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大浪淘沙胡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值