前言

MQTT协议是IBM开发的一个即时通讯协议,有可能成为物联网的重要组成部分,http://mqtt.org/。

MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. For example, it has been used in sensors communicating to a broker via satellite link, over occasional dial-up connections with healthcare providers, and in a range of home automation and small device scenarios. It is also ideal for mobile applications because of its small size, low power usage, minimised data packets, and efficient distribution of information to one or many receivers

通过https://github.com/mqtt/mqtt.github.io/wiki/servers 找到官方推荐的服务端软件,比如:Apache Apollo,

通过https://github.com/mqtt/mqtt.github.io/wiki/libraries可以找到推荐的客户端类库,比如:Eclipse Paho Java

MQTTnet

MQTTnet 是MQTT协议的.NET 开源类库。

MQTTnet is a .NET library for MQTT based communication. It provides a MQTT client and a MQTT server. The implementation is based on the documentation from http://mqtt.org/.

通过Nuget搜索MQTT找到了MQTTnet,它不是下载量最多的,也不在官方推荐列表中,主要是因为同时支持客户端和服务端,所以开始下载试用,结果证明有坑,源码在vs2015中不能打开,客户端示例接收不到消息。

开源地址:https://github.com/chkr1011/MQTTnet

首先把官方的控制台程序改成winform的,界面如下:

 public partial class Form1 : Form
{ private MqttServer mqttServer = null;
private MqttClient mqttClient = null; public Form1()
{
InitializeComponent();
} private void button_启动服务端_Click(object sender, EventArgs e)
{ MqttTrace.TraceMessagePublished += MqttTrace_TraceMessagePublished; if (this.mqttServer == null)
{
try
{
var options = new MqttServerOptions
{
ConnectionValidator = p =>
{
if (p.ClientId == "SpecialClient")
{
if (p.Username != "USER" || p.Password != "PASS")
{
return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
}
} return MqttConnectReturnCode.ConnectionAccepted;
}
}; mqttServer = new MqttServerFactory().CreateMqttServer(options); }
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return; }
}
mqttServer.Start(); this.txt_服务器.AppendText( $">> 启动成功..." + Environment.NewLine);
} private void MqttTrace_TraceMessagePublished(object sender, MqttTraceMessagePublishedEventArgs e)
{
this.Invoke(new Action(() =>
{
this.txt_服务器.AppendText($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}" + Environment.NewLine);
if (e.Exception != null)
{
this.txt_服务器.AppendText( e.Exception + Environment.NewLine);
}
}));
} private void button_停止服务端_Click(object sender, EventArgs e)
{
if (mqttServer != null)
{
mqttServer.Stop();
}
this.txt_服务器.AppendText( $">> 停止成功" + Environment.NewLine);
} private async void button_启动客户端_Click(object sender, EventArgs e)
{
if (this.mqttClient == null)
{
var options = new MqttClientOptions
{
Server = "192.168.2.54",
ClientId = "zbl",
CleanSession = true
};
this.mqttClient = new MqttClientFactory().CreateMqttClient(options);
this.mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
this.mqttClient.Connected += MqttClient_Connected;
this.mqttClient.Disconnected += MqttClient_Disconnected; }
try
{
await this.mqttClient.ConnectAsync();
}
catch(Exception ex)
{
this.txt_客户端.AppendText( $"### CONNECTING FAILED ###" + Environment.NewLine);
} } private void MqttClient_Connected(object sender, EventArgs e)
{ this.Invoke(new Action( async () =>
{ this.txt_客户端.AppendText( $"### CONNECTED WITH SERVER ###" + Environment.NewLine);
await this.mqttClient.SubscribeAsync(new List<TopicFilter>{
new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
});
this.txt_客户端.AppendText($"### SUBSCRIBED ###" + Environment.NewLine);
}));
} private void MqttClient_Disconnected(object sender, EventArgs e)
{
this.Invoke(new Action(() =>
{
this.txt_客户端.AppendText( $"### DISCONNECTED FROM SERVER ###" + Environment.NewLine); }));
} private void MqttClient_ApplicationMessageReceived(object sender, MQTTnet.Core.MqttApplicationMessageReceivedEventArgs e)
{
this.Invoke(new Action(() =>
{
this.txt_客户端.AppendText( $">> Topic:{e.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} QoS:{e.ApplicationMessage.QualityOfServiceLevel} Retain:{e.ApplicationMessage.Retain}" + Environment.NewLine); }));
} private async void button_停止客户端_Click(object sender, EventArgs e)
{
if (this.mqttClient != null)
{
await this.mqttClient.DisconnectAsync();
}
this.txt_客户端.AppendText( $">> 停止成功" + Environment.NewLine);
} private async void button_发送_Click(object sender, EventArgs e)
{ //var options = new MqttClientOptions
//{
// Server = "localhost"
//};
//var client = new MqttClientFactory().CreateMqttClient(options); //await client.ConnectAsync(); var applicationMessage = new MqttApplicationMessage(this.txt_topic.Text,
Encoding.UTF8.GetBytes(this.txt_message.Text), MqttQualityOfServiceLevel.AtMostOnce, false); await this.mqttClient.PublishAsync(applicationMessage); } private void button_清空服务端_Click(object sender, EventArgs e)
{
this.txt_服务器.Text = "";
}
}

需要注意的是按照作者说明是

1
2
3
4
5
6
7
8
9
10
11
12
13
while (true)
{
    Console.ReadLine();
 
    var applicationMessage = new MqttApplicationMessage(
        "A/B/C",
        Encoding.UTF8.GetBytes("Hello World"),
        MqttQualityOfServiceLevel.AtLeastOnce,
        false
    );
 
    await client.PublishAsync(applicationMessage);
}

 客户端死活都收不到消息,改成 MqttQualityOfServiceLevel.AtMostOnce  就可以了,找问题时尝试下载源码调试因为vs2015打不开项目也折腾了一会。这个问题提交了issues,期待作者回复。

Apache Apollo

1.下载Apollo服务器,我这里用的是Binaries for Windows。下载后解压到一个文件夹,注意路径不要包含中文,安装手册

2.创建Broker Instance,命令行cd到bin目录,执行/bin/apollo create mybroker,执行后就会在bin目录下创建mybroker文件夹。

3.运行Broker Instance,命令行cd到mybroker/bin目录,执行mybroker/bin/apollo-broker.cmd run

4.Web Administrator,地址 http://127.0.0.1:61680/ or https://127.0.0.1:61681/,默认账号 admin,密码 password

参考

搭建了MQTT服务端之后需要在Esp8266模块和手机App中分别实现客户端功能,稍后待续。。。。

 
分类: IoT

快速搭建MQTT服务器(MQTTnet和Apache Apollo)的更多相关文章

  1. 快速搭建Web服务器软件PHP+Apache+MySQL

    搭建网站或者博客,需要一个合适的 Web 服务器.除了如下能在购买的虚拟空间上进行操作外,我们也可以在自己的电脑上搞定,因为可以用来方便快捷地测试网站或者博客主题,无论是 Wordpress.Joom ...

  2. 转 【MQTT】在Windows下搭建MQTT服务器

    MQTT简介 MQ 遥测传输 (MQTT) 是轻量级基于代理的发布/订阅的消息传输协议,设计思想是开放.简单.轻量.易于实现.这些特点使它适用于受限环境.该协议的特点有: 使用发布/订阅消息模式,提供 ...

  3. MQTT实战1 - 使用Apache Apollo代理服务器实现mqtt通信

    MQTT实战1 - 使用Apache Apollo代理服务器实现mqtt通信 MQTT实战2 - 使用MQTTnet实现mqtt通信 源码下载 -> 提取码  QQ:505645074 MQTT ...

  4. MQTT再学习 -- 搭建MQTT服务器及测试

    最近在搞 PM2.5 采集,需要用到 MQTT 传输协议.协议部分看了几天的,讲的七七八八.本身在 intel 上有 写好的MQTT 的源码,现在的工作其实也就是移植到单片机上或者DM368板卡上.不 ...

  5. [Windows Azure] 使用 Windows Azure 快速搭建 Redis 服务器

    [Windows Azure] 使用 Windows Azure 快速搭建 Redis 服务器   Redis相信玩开源,大数据的朋友们并不陌生,大家最熟悉的使用者就是新浪微博,微博的整体数据缓存都是 ...

  6. 使用EMQ搭建MQTT服务器

    前言寒假的时候开始搭建mqtt服务器,一开始使用的是RabbitMQ,基于Erlang语言.但是RabbitMQ的本职工作是AMQP,MQTT只是他的一个插件功能,似乎有些大材小用,很多MQTT的功能 ...

  7. CentOS 6.5下快速搭建ftp服务器[转]

    CentOS 6.5下快速搭建ftp服务器 1.用root 进入系统 2.使用命令 rpm -qa|grep vsftpd 查看系统是否安装了ftp,若安装了vsftp,使用这个命令会在屏幕上显示vs ...

  8. Ubuntu 搭建Web服务器(MySQL+PHP+Apache)详细教程

    Ubuntu 搭建Web服务器(MySQL+PHP+Apache)详细教程 看了好多人的博客,有的不全 or 有问题,整理了一下,适合小白 新手先整理几个小问题 1.为啥使用 Linux 搭建服务器? ...

  9. 搭建MQTT服务器

    MQTT协议简介 MQTT 是一个基于发布/订阅模式的消息传输协议.它具有轻量级.开放.简单,易于实现,通信带宽要求低等特点.这些特点使得它对机器与机器的通信(M2M)以及物联网应用(IoT)来说是很 ...

随机推荐

  1. 常用CSS3

    (ಥ_ಥ)    啊啊,我的胃好疼啊.感觉最近胃又开始不舒服了.啊——果然老了呢,想当初,我也是不坏金刚之身来着呢,唉,我的可怜的小胃胃   (ಥ_ಥ) 记录几个已经常见的不能再常见的css3样式. ...

  2. sgu438-The_Glorious_Karlutka_River

    Description SGU似乎死了... 题目搬到了Codeforces... Problem - 99999438 - Codeforces Solution 动态最大流. 考虑如果不求时间, ...

  3. [SimplePlayer] 3. 视频帧同步

    Frame Rate 帧率代表的是每一秒所播放的视频图像数目.通常,视频都会有固定的帧率,具体点地说是每一帧的时间间隔都是一样的,这种情况简称为CFR(Constant Frame Rate);另外一 ...

  4. python之旅十【第十篇】paramiko模块

    paramiko模块介绍 ssh的远程连接 基于用户名密码的连接 import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_h ...

  5. Hdoj 1425.sort 题解

    Problem Description 给你n个整数,请按从大到小的顺序输出其中前m大的数. Input 每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含 ...

  6. FreeNAS:创建 CIFS 共享(权限)

    第一部分:新建账户与指定数据集权限 简单起见,本教程主要介绍带基本身份验证的 CIFS 共享,即只有输入正确的用户名和密码才可以访问共享目录.关于创建匿名共享.多用户权限管理以及域控制器相关内容,我们 ...

  7. python格式化输出的几种方式

    第一种  字符串拼接  就不写了 下面的是 第二 第三 第四种 name = input("name:") age = int(input("age:")) p ...

  8. GO语言系列(五)- 结构体和接口

    结构体(Struct) Go中struct的特点 1. 用来自定义复杂数据结构 2. struct里面可以包含多个字段(属性) 3. struct类型可以定义方法,注意和函数的区分 4. struct ...

  9. mysql MHA架构搭建过程

    [环境介绍] 系统环境:Red Hat Enterprise Linux 7 + 5.7.18 + MHA version 0.57 系统 IP 主机名 备注 版本 xx系统 192.168.142. ...

  10. esnext:Function.prototype.toString 终于有规范了

    从 ES1 到 ES5 的这 14 年时间里,Function.prototype.toString 的规范一字未变: An implementation-dependent representati ...