我的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();
 }
相关推荐
红树林07几秒前
渗透测试之sql注入--报错注入
数据库·sql·安全·web安全
菜鸟小九26 分钟前
mysql(锁)
数据库·mysql·oracle
c***421034 分钟前
【Sql Server】随机查询一条表记录,并重重温回顾下自定义函数的封装和使用
数据库·性能优化
q***44811 小时前
PostgreSQL的备份方式
数据库·postgresql
v***59831 小时前
【SQL Server】超详细SQLServer日期转换、字符串、数学、聚合等常用函数大全(最新版)
数据库·sqlserver
q***23571 小时前
python的sql解析库-sqlparse
数据库·python·sql
q***92512 小时前
sql实战解析-sum()over(partition by xx order by xx)
数据库·sql
gladiator+2 小时前
Redis之BigKey的常见问题以及大厂相关面试题
java·数据库·redis
合方圆~小文2 小时前
AI摄像头精准识别技术依赖于深度算法
数据结构·数据库·数码相机·模块测试
tanxiaomi2 小时前
Redis相关面试题
数据库·redis·缓存