1、什麼是MQTT? MQTT(Message Queuing Telemetry Transport,消息隊列遙測傳輸協議),是一種基於發佈/訂閱(publish/subscribe)模式的"輕量級"通訊協議,該協議構建於TCP/IP協議上,由IBM在1999年發佈。MQTT最大優點在於,可以以極 ...
1、什麼是MQTT?
MQTT(Message Queuing Telemetry Transport,消息隊列遙測傳輸協議),是一種基於發佈/訂閱(publish/subscribe)模式的"輕量級"通訊協議,該協議構建於TCP/IP協議上,由IBM在1999年發佈。MQTT最大優點在於,可以以極少的代碼和有限的帶寬,為連接遠程設備提供實時可靠的消息服務。作為一種低開銷、低帶寬占用的即時通訊協議,使其在物聯網、小型設備、移動應用等方面有較廣泛的應用。
MQTT是一個基於客戶端-伺服器的消息發佈/訂閱傳輸協議。MQTT協議是輕量、簡單、開放和易於實現的,這些特點使它適用範圍非常廣泛。在很多情況下,包括受限的環境中,如:機器與機器(M2M)通信和物聯網(IoT)。其在,通過衛星鏈路通信感測器、偶爾撥號的醫療設備、智能家居、及一些小型化設備中已廣泛使用。
(具體描述自行百度)
本文將基於.Net C# Socket WinForm MQTT 客戶端開發,實現服務端連接,消息發佈,消息訂閱,取消訂閱及接收服務端返回消息功能。
2、連接服務端
客戶端連接服務端,啟動非同步接收服務端消息。
1 //連接選項 2 var option = new MQTT.MQTTClientOption() 3 { 4 ClientId = this.txtClientId.Text, 5 IpString = this.txtServer.Text, 6 Port = Convert.ToInt32(this.txtPort.Text), 7 UserName = this.txtUserName.Text, 8 Password = this.txtPassword.Text 9 }; 10 //實例客戶端 11 this.mqttClient = new MQTT.MQTTClient(); 12 this.mqttClient.ClientReceived += MqttClient_ClientReceived; 13 var result = await this.mqttClient.ConnectAsync(option); 14 if(result.State == false) 15 { 16 MessageBox.Show(result.Fail, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); 17 return; 18 } 19 //開始接收 20 this.mqttClient.BeginReceive();
3、發佈消息
客戶端向服務端發送消息,主要包括主題,內容及消息質量。
發送消息程式
1 private short _PacketId = 1; 2 private async void BtnPublish_Click(object sender, EventArgs e) 3 { 4 this.btnPublish.Enabled = false; 5 this.Cursor = Cursors.WaitCursor; 6 try 7 { 8 short qos = 0; 9 if (rdbLevel1.Checked) 10 qos = 1; 11 if (rdbLevel2.Checked) 12 qos = 2; 13 14 var data = new MQTT.PublishEntity() 15 { 16 Topic = this.txtTopic.Text, 17 Reload = System.Text.Encoding.UTF8.GetBytes(this.txtContent.Text), 18 Qos = qos, 19 PacketId=_PacketId 20 }; 21 var result = await this.mqttClient.PublishAsync(data,false); 22 if(result.State == false) 23 { 24 this.AppendText("發送失敗:" + result.Fail); 25 return; 26 } 27 this._PacketId++; 28 this.AppendText("發送成功,返回結果:" + result.Result); 29 } 30 finally 31 { 32 this.btnPublish.Enabled = true; 33 this.Cursor = Cursors.Default; 34 } 35 }
4、訂閱消息
客戶端訂閱消息,主要包括過濾主題及消息質量。
訂閱消息方法:
1 private async void BtnSubscribe_Click(object sender, EventArgs e) 2 { 3 this.btnSubscribe.Enabled = false; 4 this.Cursor = Cursors.WaitCursor; 5 6 try 7 { 8 string fail = string.Empty; 9 10 short qos = 0; 11 if (rdbQos1.Checked) 12 qos = 1; 13 if (rdbQos2.Checked) 14 qos = 2; 15 16 MQTT.SubscribeEntity entity = new MQTT.SubscribeEntity(); 17 entity.Filter = this.txtFilter.Text; 18 entity.Qos = qos; 19 20 this.AppendText("開始訂閱..."); 21 //if (mqttClient.Subscribe(this.txtFilter.Text, qos, out result, out fail) == false) 22 //{ 23 // this.AppendText(fail); 24 // return; 25 //} 26 var result = await mqttClient.SubscribeAsync(entity.Filter,entity.Qos); 27 if (result.State == false) 28 { 29 this.AppendText(result.Fail); 30 return; 31 } 32 33 this.AppendText("訂閱成功!返回結果:" + result.Result); 34 MQTT.SubscribeHelper.Save(entity); 35 36 DataRow drData = this.dtSubscribes.NewRow(); 37 drData["Id"] = entity.Id; 38 drData["Filter"] = entity.Filter; 39 drData["Qos"] = entity.Qos; 40 drData["Count"] = 0; 41 dtSubscribes.Rows.Add(drData); 42 } 43 finally 44 { 45 this.btnSubscribe.Enabled = true; 46 this.Cursor = Cursors.Default; 47 } 48 }
5、取消訂閱
客戶端取消某一訂閱消息。雙擊訂閱消息行,取消訂閱消息。
取消訂閱方法:
1 private async void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) 2 { 3 if (this.dataGridView1.CurrentCell == null) 4 return; 5 6 DataRowView drv = this.dataGridView1.CurrentRow.DataBoundItem as DataRowView; 7 if (drv == null) 8 return; 9 10 if (MessageBox.Show("確認取消當前選擇:" + drv["Filter"].ToString() + " 訂閱?", "確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) 11 return; 12 try 13 { 14 this.AppendText("開始取消訂閱..."); 15 var result = await mqttClient.UnSubscribeAsync(drv["Filter"].ToString()); 16 if (result.State == false) 17 { 18 this.AppendText(result.Fail); 19 return; 20 } 21 this.AppendText("取消訂閱成功!返回結果:" + result.Result); 22 MQTT.SubscribeHelper.Delete(drv["Id"].ToString()); 23 this.dataGridView1.Rows.RemoveAt(this.dataGridView1.CurrentCell.RowIndex); 24 } 25 catch (Exception ex) 26 { 27 this.AppendText("取消訂閱異常:" + ex.ToString()); 28 } 29 30 }
6、接收服務端消息
客戶端接收服務端轉發過來的消息。
1 private void MqttClient_ClientReceived(MQTT.MQTTClient client, MQTT.ReceiveResult receive) 2 { 3 if(receive.Data != null) 4 this.AppendText("DataReceived state="+receive.State+" topic="+ receive.Data.Topic + " content=" + System.Text.Encoding.UTF8.GetString(receive.Data.Reload)); 5 else if(receive.State) 6 this.AppendText("DataReceived state=" + receive.State + " result=" + receive.Result); 7 else 8 this.AppendText("DataReceived state=" + receive.State + " fail=" + receive.Fail); 9 }
至此,客戶端工具主要功能簡介完畢,不當之處,歡迎指正!
客戶端下載地址(碼雲伺服器):https://gitee.com/ShiQuan25/full-product-management/raw/master/WinMQTTClient/WinMQTTClient.zip
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接。如有問題,可以郵件:[email protected] QQ:896374871 聯繫我,非常感謝。