• c# MQTT操作类


     public class KdMqttClient
        {
            private static KdMqttClient MQInstance;
            private MqttClient MQClient;
            private string clientId;
    
            public delegate void ReceiveHandle(string msg);
            public ReceiveHandle ReceiveCall;
    
    
            public static KdMqttClient Instance
            {
                get
                {
                    if (MQInstance == null)
                    {
                        MQInstance = new KdMqttClient();
                       
                    }
    
                    return MQInstance;
                }
            }
     
            public void DisposeMQInstance()
            {
                Close();
    
                MQClient = null;
            }
     
            public void Connect(string address,int port,string user,string pwd)
            {
    
                if (MQClient==null)
                {
                    MQClient = new MqttClient(address, port, false, null, null, MqttSslProtocols.None, null);
                    MQClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
                    clientId = Guid.NewGuid().ToString();
                }
    
                MQClient.Connect(clientId, user, pwd);
    
            }
    
            public void Close()
            {
                try
                {
                    if (MQClient == null)
                        return;
    
                    if (MQClient.IsConnected)
                    {
                        MQClient.Disconnect();
                    }
    
                }
                catch
                {
    
                }
    
            }
    
            public void SubTopic(string topic)
            {
                MQClient.Subscribe(new string[] { topic }, new byte[] { 2 });
            }
    
            public void Unsubscribe(string topic)
            {
                if (MQClient == null)
                    return;
    
                MQClient.Unsubscribe(new string[] { topic });
            }
    
            void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
            {
                string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
    
                if (ReceiveCall != null)
                {
                    ReceiveCall(ReceivedMessage);
                }
            }
        }
  • 相关阅读:
    Educational Codeforces Round 80 (Rated for Div. 2)
    寒假集训
    HDU-4609 3-idiots
    部分分式展开法
    线性同余方程组
    爬取哔哩哔哩python搜索结果
    数据可视化练习题
    python正则表达式
    git的安装和基础知识
    python学习计划
  • 原文地址:https://www.cnblogs.com/czly/p/14427443.html
Copyright © 2020-2023  润新知