这是我做的第一个物联网项目,也是第一个项目,当时是真的很慌张,一转眼也过去这么久了,记录一下吧,是可以直接用的代码,把地址和订阅的topic换成自己需要的、变量在data里声明一下就可以了,这段代码已经跟我一起开发了pc端、app和小程序了,它已经长大了~~
// mqtt initMqtt() { if (this.client != '' || this.client != null) { this.client == null } let that = this; // #ifdef H5 const connectUrl = 'wss://xxxxxx:82' // #endif // #ifdef MP-WEIXIN||APP-PLUS const connectUrl = 'wxs://xxxxxx:82' // #endif // 获取终端标识 var clientId = `app_${Math.random().toString(16).slice(3)}`; //客户端标识 var mqtt = require("@/utils/mqtt.min.js"); const options = { clean: true, // 保留回话 connectTimeout: 4000, // 超时时间 // 认证信息 clientId, username: 'tczpmall', password: 'tczpmall0607', } that.client = mqtt.connect(connectUrl, options); that.client.on("connect", function() { // console.log("连接成功...."); }); //如果连接错误,打印错误 that.client.on("error", function(err) { console.log("err=>", err); that.client.end(); }); }, // 系统消息 mqttReceive() { const that = this; let topic = `mallSysMsg/${that.user.mallUserUid}`; //要接收的主题 that.client.subscribe(topic, function(err) { if (!err) { // console.log("subscribe success!", topic); } else { //打印错误 console.log("err", err); } }); that.client.on("message", function(topic, message) { console.log("message", message); }); }