设为首页 收藏本站
查看: 2031|回复: 0

[经验分享] 快速搭建MQTT服务器(MQTTnet和Apache Apollo)

[复制链接]

尚未签到

发表于 2017-12-24 06:03:21 | 显示全部楼层 |阅读模式
前言
  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>
  通过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的,界面如下:
DSC0000.png


DSC0001.gif DSC0002.gif
  

public partial>
{  

  

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 = "";
  
}
  
}
  


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

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
DSC0003.png


参考


  • MQTT协议的简单介绍和服务器的安装,
  • 编写和MQTT服务器通信的Android客户端程序,
  • MQTT】在Windows下搭建MQTT服务器
  搭建了MQTT服务端之后需要在Esp8266模块和手机App中分别实现客户端功能,稍后待续。。。。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-427378-1-1.html 上篇帖子: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException 下篇帖子: Apache Shiro 用户信息保存在session方案
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表