我的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();
 }
相关推荐
dot.Net安全矩阵1 小时前
.NET | 剖析通过 TcpClient 实现内网端口转发
服务器·网络·tcp/ip·安全·.net
时雨h1 小时前
30天面试打卡计划 2024-12-25 26 27 面试题
java·开发语言·数据库
TDengine (老段)3 小时前
TDengine 新功能 VARBINARY 数据类型
大数据·c语言·数据库·时序数据库·tdengine·涛思数据
yuenblue5 小时前
什么是ondelete cascade以及使用sqlite演示ondelete cascade使用案例
数据库·sqlite
howard_shooter5 小时前
Oracle Managed Files(OMF)
数据库·oracle
yangfeipancc6 小时前
数据库-用户管理
android·数据库
两点王爷8 小时前
Java读取csv文件内容,保存到sqlite数据库中
java·数据库·sqlite·csv
凡人的AI工具箱9 小时前
每天40分玩转Django:Django部署概述
开发语言·数据库·后端·python·django
2401_871213309 小时前
mysql之MHA
数据库·mysql
言之。10 小时前
【MySQL】事务
数据库·mysql