MQTT.js 是一个开源项目,支持 nodejs 和 Browser js ,这里对比一下 nodejs 和 Browser js 的用法:注:nodejs是运行在webserver的js,Browser js意思是运行在浏览器上的js,也就是H5用到的js
注:目前项目方已经提供 CDN,不需要自己打包 https://unpkg.com/mqtt/dist/mqtt.min.js
url:ws://xxxxx:port/mqtt
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>文件链接:<a href=" https://unpkg.com/mqtt/dist/mqtt.min.js"> https://unpkg.com/mqtt/dist/mqtt.min.js</a> </p> <p>打开控制台看打印的信息</p> <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> <script> function randomName(len) { var len = len || 23; var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = chars.length; var str = ''; for (let i = 0; i < len; i++) { str += chars.charAt(Math.floor(Math.random() * maxPos)); } return new Date().getTime() + str; } // 请确保仅在浏览器中将此捆绑包与ws 或 wssURL 一起使用。其他 URL 类型将失败 const connectUrl = 'ws://broker.emqx.io:8083/mqtt' const options = { connectTimeout: 4000, reconnectPeriod: 1000, clientId: 'emqx_test', username: 'emqx_test', password: 'emqx_test', clean: true, } options.clientId = randomName(16); // var client = mqtt.connect(connectUrl);//连接的时候不用 options 也可以 var client = mqtt.connect(connectUrl, options); // topic 是任意字符串,如果使用常见名字如 demo,可能会收到别人测试时发送的数据 const topic = "myTopic125"; client.on("connect", () => { console.log('连接成功'); }); client.subscribe(topic, () => { console.log('订阅了主题:', { topic }); }) client.on('message', (topic, msg) => { console.log(`topic: ${topic}`); console.log(`message: ${msg.toString()}`); }); client.on("close", () => { console.log('已经断开连接'); }); // 每隔2秒发送一次消息 setInterval(() => { client.publish(topic, "" + new Date()); }, 2000); </script> </body> </html>
运行结果:
options.clientId = randomName(16); 是把 clientId 改为随机数,因为如果 clientId 是写死的值,mqtt 会频繁重连:参考文档:
[1] https://www.dazhuanlan.com/jimholms/topics/1108692
[2] https://blog.csdn.net/qq_17627195/article/details/124492512
[3] https://www.zkii.net/tech/arduino/4013.html
标签:console,client,topic,mqtt,html,使用,var,js From: https://www.cnblogs.com/sunshine233/p/16873379.html