我的MQTT操作类(M2Mqtt.Net)

类本体

4.3.0

csharp 复制代码
public   class MQTTMain
    {
        public   MqttClient mqttClient =null ; 
        public   bool MQTTMainConnect(string MenZuNo, string ServerIP, int ServerPort, string UserName, string Pwd)
        {
            try
            {
                string EMQX_CLIENT_ID = $"称重端-{MenZuNo}-{OPCommon.PCControl.GetPCInfos.GetMachineName()}";
                mqttClient = new MqttClient(ServerIP, ServerPort, false, null, null, MqttSslProtocols.None);
                mqttClient.Connect(EMQX_CLIENT_ID, UserName, Pwd);//需要录入账号密码
                return true; 
            }
            catch (Exception ex)
            {
                OPCommon.LogWrite.WriteLog("MQTT链接错误,信息是:"+ex.Message);
                return false;

            } 
        }
        /// <summary>
        /// 发布主题
        /// </summary>
        /// <param name="MenZuNo"></param>
        /// <param name="ServerIP"></param>
        /// <param name="ServerPort"></param>
        /// <param name="UserName"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public   bool MQTTMainPublish(string Zhuti, string MsgInfo )
        {
            try
            {
                mqttClient.Publish(Zhuti, System.Text.Encoding.UTF8.GetBytes(MsgInfo), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
                return true;
            }
            catch (Exception ex)
            {
                OPCommon.LogWrite.WriteLog("MQTT发送错误,信息是:" + ex.Message);
                return false;
            }
        }

连接的应用

csharp 复制代码
 /// <summary>
        /// MQTT链接重新连接
        /// </summary>
        public void ThisMQTTConntect()
        {
            if (ThisMQTTS.mqttClient == null || !ThisMQTTS.mqttClient.IsConnected)
            {
                ThisMQTTS.MQTTMainConnect(GModel.MainSetupAll.BangNo, GModel.MainSetupAll.ServerIp, GModel.MainSetupAll.ServerPort, GModel.MainSetupAll.ServerUser, GModel.MainSetupAll.Pwd);
            }
            if (ThisMQTTS.mqttClient != null && ThisMQTTS.mqttClient.IsConnected)
            {
                ThisMQTTS.mqttClient.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
                ThisMQTTS.mqttClient.ConnectionClosed += TryReconnectAsync;
                ThisMQTTS.mqttClient.Subscribe(new string[] { GModel.DingyueZhuti }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });//订阅主题
            }
        }

断开重连:

csharp 复制代码
 private void TryReconnectAsync(object sender, EventArgs ex)
        {
            if (!ThisMQTTS.mqttClient.IsConnected && !IsThisClose)
            {
                OPCommon.LogWrite.WriteLog($"{this.Name}当前断开");
                Thread.Sleep(2000);
                Thread retryThread = new Thread(new ThreadStart(delegate
                {
                    OPCommon.LogWrite.WriteLog($"{this.Name}第一次重连");
                    ThisMQTTConntect();
                    if (!ThisMQTTS.mqttClient.IsConnected)
                    {
                        OPCommon.LogWrite.WriteLog($"{this.Name}第二次重连!");
                        Thread.Sleep(5000);
                        ThisMQTTConntect();
                    }
                    else
                    {
                        OPCommon.LogWrite.WriteLog($"{this.Name}第一次重连成功!");
                    }
                }));
                retryThread.Start();
            } 
        } 

MQTT数据接受

csharp 复制代码
/// <summary>
        ///  MQTT操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            //string topic = e.Topic.ToString();//主题内容
            
            string MsgFromMQTT = System.Text.Encoding.UTF8.GetString(e.Message);//数据内容
        }

发送数据

csharp 复制代码
 if (ThisMQTTS.mqttClient != null && ThisMQTTS.mqttClient.IsConnected)
 {
        ThisMQTTS.MQTTMainPublish(GModel.DingyueZhuti, SetToServer);
        OPCommon.LogWrite.WriteLog("数据发送成功:" + SetToServer);
        ChengzhongMainWath.Restart();
 }
相关推荐
WineMonk1 小时前
.NET WPF CommunityToolkit.Mvvm框架
.net·wpf·mvvm
superman超哥1 小时前
04 深入 Oracle 并发世界:MVCC、锁、闩锁、事务隔离与并发性能优化的探索
数据库·oracle·性能优化·dba
用户8007165452001 小时前
HTAP数据库国产化改造技术可行性方案分析
数据库
界面开发小八哥1 小时前
界面控件DevExpress WPF中文教程:Data Grid——卡片视图设置
.net·wpf·界面控件·devexpress·ui开发
engchina2 小时前
Neo4j 和 Python 初学者指南:如何使用可选关系匹配优化 Cypher 查询
数据库·python·neo4j
engchina2 小时前
使用 Cypher 查询语言在 Neo4j 中查找最短路径
数据库·neo4j
尘浮生2 小时前
Java项目实战II基于Spring Boot的光影视频平台(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·后端·maven·intellij-idea
威哥爱编程2 小时前
SQL Server 数据太多如何优化
数据库·sql·sqlserver
小华同学ai2 小时前
AJ-Report:一款开源且非常强大的数据可视化大屏和报表工具
数据库·信息可视化·开源
Acrelhuang2 小时前
安科瑞5G基站直流叠光监控系统-安科瑞黄安南
大数据·数据库·数据仓库·物联网