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);
                }
            }
        }
  • 相关阅读:
    23种设计模式彩图
    Win10间歇性卡顿
    RDMA
    mii-tool与ethtool的用法详解
    linux下模拟CPU占用100%小程序
    Linux SNMP 监控一些常用OID
    SNMP协议介绍
    set排序(个人模版)
    TSP(个人模版)
    树的重心(个人模版)
  • 原文地址:https://www.cnblogs.com/czly/p/14427443.html
Copyright © 2011-2022 走看看