MqttNet 通讯
2018-10-19 15:12 Evan.Pei 阅读(1484) 评论(0) 编辑 收藏 举报MQTT,IBM发明的物联网通讯协议基于tcp ip , 收集传感器上的数据。
下图理解: broker 这里有很多消息,根据主题不同来进行区分,它这里可以保管所有连过来的客户端的数据,然后客户端,通过订阅broker它有的主题进行获取数据。
学习网址:https://github.com/chkr1011/MQTTnet/wiki/Client
broker网址 代理:http://www.mqtt-dashboard.com/
开发(只需客户端):
vs2015
1.添加引用本文MQTTnet2.8.4(管理NuGet程序包)
2.界面
3.代码
using MQTTnet; using MQTTnet.Client; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace server { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public static IMqttClient mqttClient = null; public static IMqttClientOptions options = null; private void Form1_Load(object sender, EventArgs e) { //实例化对象 var factory = new MqttFactory(); mqttClient = factory.CreateMqttClient(); mqttClient.Connected += SubscribeTopic; mqttClient.Disconnected += MqttClient_Disconnected; mqttClient.ApplicationMessageReceived += Receive; //配置参数 //options = new MqttClientOptionsBuilder() // .WithClientId(Guid.NewGuid().ToString().Substring(0, 5)) // .WithTcpServer("broker.hivemq.com") // .WithCredentials("bud", "%spencer%") // .WithTls() // .WithCleanSession() // .Build(); options = new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").Build(); //连接 Task.Run(async () => { await ConnectMqtt(); }); } public async Task ConnectMqtt() { try { MqttClientConnectResult x = await mqttClient.ConnectAsync(options); } catch (Exception ex) { Invoke((new Action(() => { textBox2.Text = $"连接到MQTT服务器失败!" + Environment.NewLine + ex.Message + Environment.NewLine; }))); } } //接收消息 public async void Receive(object sender, MqttApplicationMessageReceivedEventArgs e) { try { Invoke((new Action(() => { //textBox2.AppendText("### RECEIVED APPLICATION MESSAGE 接收消息 ###"); textBox2.AppendText($"Topica(主题) = {e.ApplicationMessage.Topic}" + "\t\n"); textBox2.AppendText($"Payloada(内容) = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}" + "\t\n"); //textBox2.AppendText($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); //textBox2.AppendText($"+ Retain = {e.ApplicationMessage.Retain}"); }))); } catch (Exception ex) { Invoke((new Action(() => { textBox2.Text = ex.Message; }))); } } //连接成功 public async void SubscribeTopic(object sender, EventArgs e) { Invoke((new Action(() => { label2.Text = "连接成功"; }))); } /// <summary> /// 连接失败 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public async void MqttClient_Disconnected(object sender, EventArgs e) { Invoke((new Action(() => { textBox2.AppendText("连接失败!" + Environment.NewLine); }))); //重新连接 await Task.Delay(TimeSpan.FromSeconds(3)); try { await mqttClient.ConnectAsync(options); Invoke((new Action(() => { textBox2.AppendText("连接成功!"); }))); } catch { Invoke((new Action(() => { textBox2.AppendText("连接失败!"); }))); } } /// <summary> /// 订阅消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { string topic = textBox1.Text; mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build()); textBox2.AppendText("### 订阅" + topic + "成功 ###\t\n"); } /// <summary> /// 释放资源 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { mqttClient.Dispose(); textBox2.AppendText("### 断开连接###\t\n"); } /// <summary> /// 发布一个主题内容 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { var message = new MqttApplicationMessageBuilder() .WithTopic(textBox3.Text) .WithPayload(textBox4.Text) .WithExactlyOnceQoS() .WithRetainFlag() .Build(); mqttClient.PublishAsync(message); } } }
4.运行效果
这些数据就是根据你的主题从http://www.mqtt-dashboard.com/ 代理取来,你也可以发布主题的内容,别人也可以订阅你的主题,取数据。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构