深圳全飞鸿

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 435|回复: 1
打印 上一主题 下一主题

MQTT/网页访问的调试

[复制链接]

800

主题

1379

帖子

7704

积分

版主

Rank: 7Rank: 7Rank: 7

积分
7704
跳转到指定楼层
楼主
发表于 2023-8-10 13:40:22 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
注意:
1、 网页是用webSockets方式与MQTT交互的,所以MQTT服务端要支持websockets的方式
2、调通时的画面:


网页代码:const client = mqtt.connect('ws://localhost:8083/mqtt');
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.   <meta charset="UTF-8">
  5.   <title>MQTT.js Example</title>
  6.   <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
  7. </head>
  8. <body>
  9.   <h1>MQTT.js Example</h1>
  10.   <button onclick="connect()">Connect</button>
  11.   <button onclick="disconnect()">Disconnect</button>
  12.   <button onclick="subscribe()">Subscribe</button>
  13.   <button onclick="publish()">Publish</button>
  14.   <div id="message"></div>
  15.   <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
  16.   <script>
  17.     // 创建一个MQTT客户端对象
  18.     const client = mqtt.connect('ws://localhost:8083/mqtt');

  19.     // 当连接成功时执行以下函数
  20.     client.on('connect', function() {
  21.       console.log('Connected to the broker');
  22.       subscribe();
  23.     });

  24.     // 当收到消息时执行以下函数
  25.     client.on('message', function(topic, message) {
  26.       const output = document.getElementById('message');
  27.       output.innerHTML += `Received message on topic ${topic}: ${message.toString()}<br>`;
  28.     });

  29.     // 点击“订阅”按钮时执行以下函数
  30.     function subscribe() {
  31.       client.subscribe('test/topic', function(err) {
  32.         if (err) {
  33.           console.error(err);
  34.         } else {
  35.           console.log('subscribed');
  36.         }
  37.       });
  38.     }

  39.     // 点击“发布”按钮时执行以下函数
  40.     function publish() {
  41.       client.publish('test/topic', 'Hello World!');
  42.     }

  43.   </script>
  44. </body>
  45. </html>
复制代码


回复

使用道具 举报

800

主题

1379

帖子

7704

积分

版主

Rank: 7Rank: 7Rank: 7

积分
7704
沙发
 楼主| 发表于 2023-8-14 21:29:48 | 只看该作者
  <button onclick="connect()">采数中...</button>
  <button onclick="disconnect()">停止</button>
  <button onclick="subscribe()">Subscribe</button>
  <button onclick="publish()">测试</button>
  <div id="message"></div>       
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|nagomes  

GMT+8, 2025-5-5 03:39 , Processed in 0.026376 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

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