前言:git
MQTT是IBM開發的一個即時通信協議。MQTT是面向M2M和物聯網的鏈接協議,採用輕量級發佈和訂閱消息傳輸機制。github
你們能夠直接上GitHub下載MQQT服務的源碼,源碼地址:https://github.com/mqtt/mqtt.github.io/wiki/librariesui
主要內容:spa
官方文檔翻譯:翻譯
M2Mqtt庫提供了一個主類MqttClient,表明鏈接到代理的MQTT客戶端。您能夠鏈接到提供其IP地址或主機名的代理,以及可選的與MQTT協議相關的一些參數。代理
鏈接到代理後,您能夠使用Publish()方法向主題和Subscribe()方法發佈消息以訂閱主題並接收其上發佈的消息。code
MqttClient類是基於事件,以便您在郵件發佈到您訂閱的主題時收到一個事件。消息發佈完成後,您能夠收到事件,您已訂閱或取消訂閱主題。blog
以客戶端爲主題的例子:事件
...
// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
...
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
} ip
通常C#客戶端都是應用單例模式,下面的是我封裝的類:
1 public class MqttClientService 2 { 3 4 private static volatile MqttClientService _instance = null; 5 6 private static readonly object LockHelper = new object(); 7 8 /// <summary> 9 /// 建立單例模式 10 /// </summary> 11 /// <param name="ipAddress"></param> 12 /// <returns></returns> 13 public static MqttClientService CreateInstance(string ipAddress) 14 { 15 if (_instance == null) 16 { 17 lock (LockHelper) 18 { 19 if (_instance == null) 20 _instance = new MqttClientService(ipAddress); 21 } 22 } 23 return _instance; 24 } 25 26 /// <summary> 27 /// 實例化訂閱客戶端 28 /// </summary> 29 public MqttClient SubscribeClient { get; set; } 30 31 32 public Action<Object, MqttMsgPublishEventArgs> ClientPublishReceivedAction { get; set; } 33 34 public MqttClientService(string ipAddress) 35 { 36 // create client instance 37 SubscribeClient = new MqttClient(IPAddress.Parse(ipAddress)); 38 39 // register to message received 40 SubscribeClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived; 41 42 string clientId = Guid.NewGuid().ToString(); 43 44 SubscribeClient.Connect(clientId); 45 46 // subscribe to the topic "/home/temperature" with QoS 2 47 SubscribeClient.Subscribe(new string[] { "avatar/uploaded" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); 48 } 49 50 void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) 51 { 52 // handle message received 53 ClientPublishReceivedAction.Invoke(sender, e); 54 } 55 56 public void client_MqttMsgPublish(string publishString) 57 { 58 SubscribeClient.Publish("avatar/signed", Encoding.UTF8.GetBytes(publishString), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); 59 } 60 }
用戶只須要把訂閱的路徑寫到Subscribe便可。