MqttNet 通讯
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());
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/ 代理取来,你也可以发布主题的内容,别人也可以订阅你的主题,取数据。
MqttNet 通讯的更多相关文章
- IOT设备通讯,MQTT物联网协议,MQTTnet
一.IOT设备的特性 硬件能力差(存储能力基本只有几MB,CPU频率低连使用HTTP请求都很奢侈) 系统千差万别(Brillo,mbedOS,RIOT等) 如使用电池供电,电量消耗敏感 如果是小设备, ...
- 快速搭建MQTT服务器(MQTTnet和Apache Apollo)
前言 MQTT协议是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分,http://mqtt.org/. MQTT is a machine-to-machine (M2M)/" ...
- 使用 MQTTnet 快速实现 MQTT 通信
1 什么是 MQTT ? MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是 IBM 开发的一个即时通讯协议,有可能成为物联网的重要组成部分.MQT ...
- MQTT(一)C#使用 MQTTnet 快速实现 MQTT 通信(文末有完整Demo下载)
https://blog.csdn.net/panwen1111/article/details/79245161 目录MQTT(一)C#使用 MQTTnet 快速实现 MQTT 通信(文末有完整De ...
- HTML5笔记:跨域通讯、多线程、本地存储和多图片上传技术
最近做项目在前端我使用了很多新技术,这些技术有bootstrap.angularjs,不过最让我兴奋的还是使用了HTML5的技术,今天我想总结一些HTML5的技术,好记性不如烂笔头,写写文章可以很好的 ...
- (转)利用libcurl和国内著名的两个物联网云端通讯的例程, ubuntu和openwrt下调试成功(四)
1. libcurl 的参考文档如下 CURLOPT_HEADERFUNCTION Pass a pointer to a function that matches the following pr ...
- (转)linux下和云端通讯的例程, ubuntu和openwrt下实验成功(二)
前言: 上节用纯linux的函数实现了和云端通讯, 本节开始利用传说中的神器libcurl 话说一个网络程序员对书法十分感兴趣,退休后决定在这方面有所建树. 于是花重金购买了上等的文房四宝. 一 ...
- (转)linux下和云端通讯的例程, ubuntu和openwrt实验成功(一)
一. HTTP请求的数据流总结#上传数据, yeelink的数据流如下POST /v1.0/device/4420/sensor/9089/datapoints HTTP/1.1Host: api. ...
- 用SignalR 2.0开发客服系统[系列1:实现群发通讯]
前言 交流群:195866844 先说一下我为什么会写这个博客吧,(首先说一下,我是一个小菜鸟,讲的不好请指导 - -,) 前段时间公司的项目涉及到在B/S上使用即时通讯,(其实就是做一个B/S的客 ...
随机推荐
- JS中立即执行函数的理解
1.匿名函数不能单独定义,必须进行赋值操作或者立即执行,否则会被JS引擎定义为语法错误 function(){alert(dada);} VM229:1 Uncaught SyntaxError: U ...
- 【转载】MySQL常用系统表大全
转载地址:http://blog.csdn.net/xlxxcc/article/details/51754524 MySQL5.7 默认的模式有:information_schema, 具有 61个 ...
- spring Mybatis集成
pom文件 <?xml version="1.0" encoding="UTF-8"?><project xmlns="http:/ ...
- 从swing分发线程机制上理解多线程[转载]
本文参考了 http://space.itpub.net/13685345/viewspace-374940,原文作者:javagui 在多线程编程当中,总会提到图形编程,比如java中的swing, ...
- CodeForces 814D An overnight dance in discotheque(贪心+dfs)
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spac ...
- .net 异步函数 Async await
.net 异步函数 Async await 一旦为函数添加async关键字 该函数就是一个异步函数. 异步方法必须返回 void 或 Task<> 类型. public static ...
- mysql连接com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
现象:客户端连接服务器端mysql是没问题的,所有都木有问题,应用程序配置也没问题,但是连接就抛异常: com.mysql.jdbc.exceptions.jdbc4.CommunicationsEx ...
- [LeetCode 题解]: Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place. For example,Given 1 / \ 2 5 / \ \ 3 4 6 T ...
- Mac安装Tomcat
1. 到Tomcat官网下载,如下找tar格式文件: http://ftp.twaren.net/Unix/Web/apache/tomcat/tomcat-8/v8.0.41/bin/apache- ...
- redis内网无法连接的问题
1.修改redis服务器的配置文件 vi redis.conf 注释以下绑定的主机地址 # bind 127.0.0.1 2.修改redis服务器的参数配置 修改redis的守护进程为no ,不启用 ...