zoukankan      html  css  js  c++  java
  • 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);
                }
            }
        }
  • 相关阅读:
    拷贝数据库和VS项目
    Silverlight4-安装顺序(VS2010)
    Android开发笔记-签名
    Asp.net Core中使用Session
    Solr 排除查询
    Solr高级查询Facet
    vue.js初探
    Asp.net Core 初探(发布和部署Linux)
    Asp.net Core准备工作
    C# 生成验证码图片时消除锯齿
  • 原文地址:https://www.cnblogs.com/czly/p/14427443.html
Copyright © 2011-2022 走看看