MQTT協議(Message Queuing Telemetry Transport),翻譯過來就是遙信消息隊列傳輸,是IBM公司於1999年提出的,如今最新版本是3.1.1。MQTT是一個基於TCP的發佈訂閱協議,設計的初始目的是爲了極有限的內存設備和網絡帶寬很低的網絡不可靠的通訊,很是適合物聯網通訊html
特色:前端
1輕量,java
2能夠在網絡差的環境中使用 算法
3 使用發佈訂閱模式chrome
4遺囑apache
5消息有三種QOS(消息質量)(0只發布無論關心不收到,1最少收到一次,2確保收到一次,只一次)瀏覽器
愈來愈的的物聯網,互聯網應用在使用Mqtt協議,小黃車就是其中之一 。能夠被用做即時通信,消息隊列,消息推送(智聯招聘企業版就使用mqtt作前端的消息推送)等等。各類語言的成熟庫都有。安全
總之就是很棒,應用很廣,未來會更廣。服務器
Net也不少庫網絡
咱們這裏使用MQTTnet
using MQTTnet; using MQTTnet.Client.Connecting; using MQTTnet.Client.Disconnecting; using MQTTnet.Client.Options; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace AliyunMqtt2 { class Program { static void Main(string[] args) { string CId = "1"; //用戶標識ID String userName = "admin"; //用戶名 String passWord = "password"; //密碼 var will = new MqttApplicationMessage() { Topic = "lastwill", Payload = System.Text.Encoding.UTF8.GetBytes("我掉線了") };//定義遺囑消息 IMqttClientOptions Option = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", 61613)//地址端口號 .WithClientId(CId) //客戶端標識Id要惟一。 .WithCredentials(userName, passWord) //用戶名,密碼 .WithWillMessage(will) //加上遺囑消息 .WithCleanSession() .Build(); MqttFactory factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); //建立客戶端實例 mqttClient.Connected += (object sender, MqttClientConnectedEventArgs e) => //鏈接成功 { Console.WriteLine("鏈接成功:" + CId); var topics = new List<TopicFilter>(); topics.Add(new TopicFilter() { Topic = "傢俱/#" }); mqttClient.SubscribeAsync(topics);//訂閱 Console.WriteLine("訂閱成功:"); mqttClient.PublishAsync("傢俱/飲水機/加熱/10度", "10");//發佈 Console.WriteLine("發佈成功"); }; mqttClient.Disconnected += (object sender, MqttClientDisconnectedEventArgs e) => { Console.WriteLine("斷開鏈接:" + CId); }; mqttClient.ApplicationMessageReceived += (object sender, MqttApplicationMessageReceivedEventArgs e) => { ///收到消息 string content = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload); Console.WriteLine($"收到消息 msg={content}:"); }; mqttClient.ConnectAsync(Option); Console.ReadLine(); } } }
Mqtt須要一個Broker服務器作消息的中轉站,全部的客戶端發佈都是往broker發佈,訂閱也都是從broker訂閱
這裏咱們介紹兩種broker,免費簡單的apollo和穩定高性能的阿里雲mqtt服務
1.下載地址 http://activemq.apache.org/apollo/download.html
2.建立一個broker實例,命令行cd到bin目錄,執行/bin/apollo create mybroker,執行後就會在bin目錄下建立mybroker文件夾。
3.運行broker實例,命令行cd到mybroker/bin目錄,執行mybroker/bin/apollo-broker.cmd run
注:apollo依賴java環境。
運行成功的界面
4在瀏覽器查看鏈接的情況
在瀏覽器輸入
http://127.0.0.1:61680/ 或者 https://127.0.0.1:61681/,默認帳號 admin,密碼 password
在這裏看當前鏈接情況
1,首先要上阿里雲購買服務
購買地址https://common-buy.aliyun.com/?commodityCode=onsMqtt#/buy
購買成功進入控制檯
要是看不到實例列表的話,注意是否選擇對了區域,默認是公網,我這裏是華南區
選擇group管理
建立一個新的groupid
而後就可使用應用程序鏈接了
經常使用的net mqtt庫有MQTTnet,M2Mqtt我這裏使用 MQTTnet
使用Nuget安裝
此處的username和pwd須要從阿里雲帳戶裏面獲取
在右上角獲取
這個分別就是key和secret
而後鏈接mqtt的時候username用key
Pwd用groupid加secret的哈希算法得來
public static string HMACSHA1(string key, string dataToSign)
{
Byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(key);
HMACSHA1 hmac = new HMACSHA1(secretBytes);
Byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(dataToSign);
Byte[] calcHash = hmac.ComputeHash(dataBytes);
String calcHashString = Convert.ToBase64String(calcHash);
return calcHashString;
}
鏈接地址
在阿里雲的控制檯獲取 即接入點域名 ,這裏就再也不須要端口號了
鏈接成功
添加MqttLens
使用谷歌瀏覽器 打開谷歌插架商店搜索MqttLens 並添加到瀏覽器
添加成功後在瀏覽器打開chrome://apps/
點擊運行添加一個鏈接
測試發佈訂閱
測試成功
遺囑是mqtt的一個大特色
遺囑的原理:鏈接成功後當即每每broker發送一條消息(遺囑),但不生效,當客戶端斷開鏈接,broker檢測不到心跳時,遺囑生效。
消息格式應當是下功夫去定義的,好的topic格式可讓咱們更簡潔方便
三種符號
/ 表明層級 通常定義消息時都以 /分割成層級
好比 傢俱/飲水機/加熱
通配符+ 表明一層匹配
好比
好比有設備 飲水機想要訂閱 加熱和保溫兩個topic,只須要訂閱傢俱/飲水機/+
全通配符 # 能徹底匹配,不限制層數
Apollo 免費 數量少沒問題,數量大就不是很穩定了。並且實測時鏈接數和機器的內核數有關好比我這裏4核的 WinServer最多隻能連上512個
EMQ 國產的。也有免費版。各類服務器的版本都有,也很不錯,
這裏是官網 http://www.emqtt.com/
阿里雲微消息服務若是可靠性要求比較高,或者客戶端的數量比較大時,推薦使用阿里雲。價格也不是很貴,安全性高,穩定性很高,這裏仍是很推薦。