链接mqtt的代码
let commonApi = "http://xx:xx";
var options = {
username: 'xx',
password: 'xx',
transformWsUrl: (url, opts, client) => {
return opts.protocol && opts.protocol == 'ws' ? url + 'ws' : url;
},
clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
}
that.client = mqtt.connect(commonApi, options);
that.client.on("connect", function () {
console.log("链接成功")
that.client.subscribe('monitor/project/6', that.mqSubscribeSuccess);
})
链接带的参数当中一定要有transfromWsUrl 不然会报错
WebSocket connection to ‘ws://xxxxx‘ failed: ....404
接下来订阅
mqSubscribeSuccess() {
console.log('订阅成功')
this.client.on("message", this.onMessageArrived)
},
接收数据
onMessageArrived(topicl, message) {
console.log(topicl, message.toString())
}
注意接收的是两个参数,一个是订阅的名字,一个是mqtt返回的通道参数!!!
坑死我了!!