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);
            }
        }
    }

 

posted @ 2021-02-21 21:57  liuyong111  阅读(1189)  评论(0编辑  收藏  举报