先上图看效果
图上可以清楚的看到连接参数,以及通讯参数。废话不多说上代码app.js
import mqtt from './utils/mqtt.js'; let client = null; App({ onLaunch: function () { this.connectMqtt(); }, connectMqtt: function() { var clinet_id = parseInt(Math.random() * 100 + 888888888, 10); console.log('wx_' + clinet_id); const options = { connectTimeout: 4000, // 超时时间 clientId: 'wx_' + clinet_id, port: 8083, username: 'xxxx', password: 'xxxxx', } client = mqtt.connect('wx://xxxxxx', options) client.on('reconnect', (error) => { console.log('正在重连:', error) }) client.on('error', (error) => { console.log('连接失败:', error) }) let that = this; client.on('connect', (e) => { console.log('成功连接服务器') //订阅一个主题 client.subscribe('message.queue', { qos: 0 }, function(err) { if (!err) { console.log("订阅成功") } }) }) client.on('message', function (topic, message) { console.log('received msg:' + message.toString()); }) }, })
做这步之前要下载mqtt.js
https://unpkg.com/mqtt@2.18.8/dist/mqtt.js
https://unpkg.com/mqtt@2.18.8/dist/mqtt.min.js
完啦!调不通可以加我私人微信(caidd729)要Demo。