MQTT初入门

待我称王封你为后i 2023-06-23 12:53 59阅读 0赞
1.MQTT 入门介绍

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的”轻量级”通讯协议,该协议构建于TCP/IP协议上,由IBM在1999年发布。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

MQTT只是一个网络协议,需要一个消息中间件,目前比较有名的有Mosquitto,Apollo,RabbitMQ,Emqx等,本篇使用Mosquitto,使用的是docker eclipse-mosquitto 镜像

在这里插入图片描述

2.安装MQTT

用Centos7 + docker部署 MQTT服务,使用下载和关注次数较多的 eclipse-mosquitto 镜像,https://hub.docker.com/\_/eclipse-mosquitto

在这里插入图片描述

  1. 1.创建目录和文件
  2. mkdir -p /mosquitto/config
  3. mkdir -p /mosquitto/data
  4. mkdir -p /mosquitto/log
  5. touch /mosquitto/config/mosquitto.conf
  6. touch /mosquitto/log/mosquitto.log
  7. 2.初始化配置文件
  8. vi /mosquitto/config/mosquitto.conf,内容如下
  9. persistence true
  10. persistence_location /mosquitto/data
  11. log_dest file /mosquitto/log/mosquitto.log
  12. 3.目录授权
  13. chmod -R 755 /mosquitto
  14. 4.运行docker镜像启动mqtt
  15. docker run -it --name=mosquitto -p 1883:1883 -p 9001:9001 -v /mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf -v /mosquitto/data -v /mosquitto/log eclipse-mosquitto
  16. 5.添加配置
  17. vi /mosquitto/config/mosquitto.conf
  18. # 关闭匿名模式
  19. allow_anonymous false
  20. # 指定密码文件
  21. password_file /mosquitto/config/pwfile.conf
  22. 6.进入启动的容器shell命令行:docker exec -it mosquitto sh
  23. 7.在容器shell命令行中,利用mosquitto命令设置密码,才能访问MQTT
  24. touch /mosquitto/config/pwfile.conf
  25. chmod -R 755 /mosquitto/config/pwfile.conf
  26. # 使用mosquitto_passwd命令创建用户,第一个lxy是用户名,第二个lxy是密码
  27. mosquitto_passwd -b /mosquitto/config/pwfile.conf test test_123
  28. 8.重启mqtt容器:docker restart mosquitto
  29. 9.利用MQTT.fx进行连接,下载地址:http://mqttfx.bceapp.com/
  30. 安装MQTT.fx后,设置好连接地址,端口(默认1883),订阅一个主题,再向此主题Publish
  31. 10.mosquitto.conf完整内容如下:
  32. persistence true
  33. persistence_location /mosquitto/data
  34. log_dest file /mosquitto/log/mosquitto.log
  35. allow_anonymous false
  36. password_file /mosquitto/config/pwfile.conf
  37. #如果要让 js 通过websocket连接,则需要设置protocol为websockets
  38. #protocol websockets
3.使用MQTT.fx连接

对照上面的第9点,下载mqtt.fx 的windows64位版本,然后安装,打开软件,点击Extras-Edit Connection…
在这里插入图片描述
输入MQTT服务地址,端口,点击Generate生成一个ClientID,在User Credentials中输入用户名和密码
在这里插入图片描述
在Subscribe(订阅)中输入一个Topic名称为 test,在Publish(发布)中选中test,输入内容点击publish,能在Subscribe的右下角看到发布的内容
pis:订阅一个主题,向此主题发布内容,那么订阅者就能收到信息
在这里插入图片描述

4.JavaScript使用WebSocket连接 MQTT

想要使用websocket连接mqtt,需要mqtt服务支持websocket协议,
需要在配置文件中添加:protocol websockets
然后重启docker服务:docker restart mosquitto

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>websocket连接mqtt</title>
  6. <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
  7. <script>
  8. var hostname = '192.168.68.134', //'192.168.1.2',
  9. port = 1883,
  10. clientId = 'client-test',
  11. timeout = 10,
  12. keepAlive = 100,
  13. cleanSession = false,
  14. ssl = false,
  15. userName = 'test',
  16. password = 'test_123',
  17. topic = '/test';
  18. client = new Paho.MQTT.Client(hostname, port, clientId);
  19. //建立客户端实例
  20. var options = {
  21. invocationContext: {
  22. host: hostname,
  23. port: port,
  24. path: client.path,
  25. clientId: clientId
  26. },
  27. timeout: timeout,
  28. keepAliveInterval: keepAlive,
  29. cleanSession: cleanSession,
  30. useSSL: ssl,
  31. userName : 'test',
  32. password : 'test_123',
  33. onSuccess: onConnect,
  34. onFailure: function (e) {
  35. console.log(e);
  36. s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
  37. console.log(s);
  38. }
  39. };
  40. client.connect(options);
  41. //连接服务器并注册连接成功处理事件
  42. function onConnect() {
  43. console.log("onConnected");
  44. s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnected()}";
  45. console.log(s);
  46. client.subscribe(topic);
  47. }
  48. client.onConnectionLost = onConnectionLost;
  49. //注册连接断开处理事件
  50. client.onMessageArrived = onMessageArrived;
  51. //注册消息接收处理事件
  52. function onConnectionLost(responseObject) {
  53. console.log(responseObject);
  54. s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnectionLost()}";
  55. console.log(s);
  56. if (responseObject.errorCode !== 0) {
  57. console.log("onConnectionLost:" + responseObject.errorMessage);
  58. console.log("连接已断开");
  59. }
  60. }
  61. function onMessageArrived(message) {
  62. s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onMessageArrived()}";
  63. console.log(s);
  64. console.log("收到消息:" + message.payloadString);
  65. }
  66. function send() {
  67. var s = document.getElementById("msg").value;
  68. if (s) {
  69. s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (s) + ", from: web console}";
  70. message = new Paho.MQTT.Message(s);
  71. message.destinationName = topic;
  72. client.send(message);
  73. document.getElementById("msg").value = "";
  74. }
  75. }
  76. var count = 0;
  77. function start() {
  78. window.tester = window.setInterval(function () {
  79. if (client.isConnected) {
  80. var s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (count++) +
  81. ", from: web console}";
  82. message = new Paho.MQTT.Message(s);
  83. message.destinationName = topic;
  84. client.send(message);
  85. }
  86. }, 1000);
  87. }
  88. function stop() {
  89. window.clearInterval(window.tester);
  90. }
  91. Date.prototype.Format = function (fmt) { //author: meizz
  92. var o = {
  93. "M+": this.getMonth() + 1, //月份
  94. "d+": this.getDate(), //日
  95. "h+": this.getHours(), //小时
  96. "m+": this.getMinutes(), //分
  97. "s+": this.getSeconds(), //秒
  98. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  99. "S": this.getMilliseconds() //毫秒
  100. };
  101. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  102. for (var k in o)
  103. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
  104. k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  105. return fmt;
  106. }
  107. </script>
  108. </head>
  109. <body>
  110. <input type="text" id="msg" />
  111. <input type="button" value="Send" onclick="send()" />
  112. <input type="button" value="Start" onclick="start()" />
  113. <input type="button" value="Stop" onclick="stop()" />
  114. </body>
  115. </html>

效果如下,首先会提示连接成功,然后输入 hello world ,点击 send ,控制台会监测输出发送的信息
在这里插入图片描述

不过此版本的MQTT有点问题,要只能tcp连接,要么只能websocket连接,而且测试发现 移动智能设备无法连接上,因此又找了一个开源 MQTT 服务器 EMQ X,请看下一节

发表评论

表情:
评论列表 (有 0 条评论,59人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HTTP协议

    Hyper Text Transfer Protocol是基于请求和应答的无状态协议 一、浏览器向服务器请求一个内容 一个HTTP请求有四部分组成:请求行、请求头标、空行和

    相关 Kudu

    目录 介绍: 基础架构: 关于Tablet: Kudu与Impala集成 安装Kudu 配置Impala支持Kudu: 使用案例: 创建表: 查询Impala