- A+
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