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 通讯的更多相关文章

  1. IOT设备通讯,MQTT物联网协议,MQTTnet

    一.IOT设备的特性 硬件能力差(存储能力基本只有几MB,CPU频率低连使用HTTP请求都很奢侈) 系统千差万别(Brillo,mbedOS,RIOT等) 如使用电池供电,电量消耗敏感 如果是小设备, ...

  2. 快速搭建MQTT服务器(MQTTnet和Apache Apollo)

    前言 MQTT协议是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分,http://mqtt.org/. MQTT is a machine-to-machine (M2M)/" ...

  3. 使用 MQTTnet 快速实现 MQTT 通信

    1 什么是 MQTT ? MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是 IBM 开发的一个即时通讯协议,有可能成为物联网的重要组成部分.MQT ...

  4. MQTT(一)C#使用 MQTTnet 快速实现 MQTT 通信(文末有完整Demo下载)

    https://blog.csdn.net/panwen1111/article/details/79245161 目录MQTT(一)C#使用 MQTTnet 快速实现 MQTT 通信(文末有完整De ...

  5. HTML5笔记:跨域通讯、多线程、本地存储和多图片上传技术

    最近做项目在前端我使用了很多新技术,这些技术有bootstrap.angularjs,不过最让我兴奋的还是使用了HTML5的技术,今天我想总结一些HTML5的技术,好记性不如烂笔头,写写文章可以很好的 ...

  6. (转)利用libcurl和国内著名的两个物联网云端通讯的例程, ubuntu和openwrt下调试成功(四)

    1. libcurl 的参考文档如下 CURLOPT_HEADERFUNCTION Pass a pointer to a function that matches the following pr ...

  7. (转)linux下和云端通讯的例程, ubuntu和openwrt下实验成功(二)

    前言: 上节用纯linux的函数实现了和云端通讯, 本节开始利用传说中的神器libcurl 话说一个网络程序员对书法十分感兴趣,退休后决定在这方面有所建树. 于是花重金购买了上等的文房四宝.    一 ...

  8. (转)linux下和云端通讯的例程, ubuntu和openwrt实验成功(一)

    一.  HTTP请求的数据流总结#上传数据, yeelink的数据流如下POST /v1.0/device/4420/sensor/9089/datapoints HTTP/1.1Host: api. ...

  9. 用SignalR 2.0开发客服系统[系列1:实现群发通讯]

    前言 交流群:195866844 先说一下我为什么会写这个博客吧,(首先说一下,我是一个小菜鸟,讲的不好请指导 - -,)  前段时间公司的项目涉及到在B/S上使用即时通讯,(其实就是做一个B/S的客 ...

随机推荐

  1. hdu 折线分割平面(递推)

    题解: 首先我们考虑直线的情况: 当n=1时原来的1个平面被分割成了2个: 当n=2时原来的2个平面被分割成了4个: 当n=3时原来的4个平面被分割成了7个: 也就是说F(n)=F(n-1)+n且n= ...

  2. atom插件记录

    ├── Zen@0.16.4 写作的时候用,很给力 ├── atom-beautify@0.29.9 美化一切代码 ├── autocomplete-paths@1.0.2 路径自动提示 ├── au ...

  3. [GO]文件的读写

    首先写一个文件 package main import ( "os" "fmt" ) func WriteFile(path string) { //打开文件, ...

  4. RabbitMQ的四种ExChange

    在message到达Exchange后,Exchange会根据route规则进入对应的Queue中,message可能进入一个Queue也可能进入对应多个Queue,至于进入哪个Queue或者是说哪个 ...

  5. 从零开始学习前端JAVASCRIPT — 11、JavaScript运动模型及轮播图效果、放大镜效果、自适应瀑布流

    未完待续...... 一.运动原理 通过连续不断的改变物体的位置,而发生移动变化. 使用setInterval实现. 匀速运动:速度值一直保持不变. 多物体同时运动:将定时器绑设置为对象的一个属性. ...

  6. Discuz!X2截屏控件手动安装教程-Xproer.ScreenCapture

    版权所有 2009-2015 荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com 官方博客:http://www.cnblogs.com/xproer 产品首页:h ...

  7. RDD介绍与执行

    repartition 增加或减少分区.会产生shuffle.(多个分区分到一个分区不会产生shuffle) coalesce coalesce常用来减少分区,第二个参数是减少分区的过程中是否产生sh ...

  8. C#利用ntsd.exe关闭进程

    有时我们会发现在任务管理器中无法关闭某个进程,可以使用下面的方法强行关闭,注意不要杀掉进程表中的系统核心进程: 1.使用Windows XP/2000自带的工具 从Windows 2000开始,Win ...

  9. NET分页实现及代码

    最近在写一个关于NET的框架,写到后面果不其然的就遇到了分页,自己看了很多关于分页的并自己结合写了一个,晒出来和大家分享一下,第一次写博客望大家多多提意见啦... cs文件分页代码: Paging p ...

  10. 数独·唯一性技巧(Uniqueness)-2

    Hidden Rectangle(隐藏矩形) 在由候选数(AB)组成.可能形成UR结构的4格中,有2-3格存在额外的候选数,此时若以不存在额外候选数的一格为起点,检查其对角格所在的行和列,若该行和列其 ...