mqtt.mini.js 使用
html文件里直接调用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>mqtt.min.js 测试</title> <style> .divblock { display: inline-block; padding: 20px; border: 2px solid #00ff00; border-radius: 6px; margin: 20px 0px; user-select: none; } .divblock:active { background-color: #455072; border: 1px solid #0044ff; } </style> <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> <!-- 引处MQTT.MINI.JS库文件 --> </head> <body> <div>4路开关模块</div> <div class="divblock" onclick="Onmqtttest()">mqtt 发送</div> </body> <script> // Create a client instance var options = { //mqtt客户端的id,这里面应该还可以加上其他参数,具体看官方文档 clientId: 'mqttjs_' + (Math.random() * 1000000).toString() } //console.log(options.clientId); //浏览器采用websocket协议,host主机地址为192.168.0.200,端口为9001,路径为/mqtt var client = mqtt.connect("ws://gzlema.cn:8083/mqtt", options) // you add a ws:// url here //建立连接 client.on('connect', function () { console.log("connect success!") //订阅主题 presence client.subscribe('presence', function (err) { if (!err) { console.log("subscribe success!") } else { //打印错误 console.log(err) } }) }) //如果连接错误,打印错误 client.on('error', function (err) { console.log(err) client.end() }) //如果client订阅主题成功,那么这里就是当接收到自己订阅主题的处理逻辑 client.on('message', function (topic, message) { // message is Buffer,此处就是打印消息的具体内容 console.log('-> ' + message.toString()) }) // 用户程序点击事件 function Onmqtttest() { message = "message from browser with websocket"; // 消息内容 //发布主题presence,消息内容为Hello mqtt,订阅与推送一样自发自收 client.publish('presence', 'Hello mqtt ' + message) } </script> </html>