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