MQTT 是用于物联网 (IoT) 的 OASIS 标准消息传递协议。它被设计为一种极其轻量级的发布/订阅消息传输,非常适合连接具有小代码占用空间和最小网络带宽的远程设备。
那么如何在VUE项目中使用MQTT协议
npm install mqtt --save
新建mqtt.js文件,将配置填写好,具体如下
export default class myMqtt {
const mqttOptions = {
host: '192.168.0.133',
port: 8083,
username: 'admin',
password: 'public',
protocolId: 'client_from_kk_web'
}
constructor (topic, callBack) {
this.options = mqttOptions
this.topic = topic
this.mqttConnect()
this.callBack = callBack
}
mqttConnect () {
const client = new Paho.MQTT.Client(this.options.host, this.options.port, this.options.protocolId)// params: host port clientId
const _options = {
// Params:timeout userName password willMessage keepAliveInterval cleanSession useSSL invocationContext onSuccess onFailure hosts ports mqttVersion
userName: this.options.username,
password: this.options.password,
timeout: 10, // connect timeout
keepAliveInterval: 60, // connect keepalive time
onSuccess: () => {
console.log(`连接成功,订阅主题 ${this.topic}`);
client.subscribe(this.topic, {qos: 2}) // subscribe theme // QOS(0:at most once; 1: at least once; 2: exactly once )
},
onFailure: (error) => {
console.log('连接失败', error)
}
}
client.onConnectionLost = responseObject => {
this.onConnectionLost(responseObject)
}
client.onMessageArrived = message => {
this.callBack && this.callBack(message.payloadString)
}
client.connect(_options)
this.destroyed = client.disconnect
}
onConnectionLost (responseObject) {
if (responseObject.errorCode !== 0) {
console.log(`主题${this.topic}连接已断开,正在重新连接。。。`);
this.mqttConnect()
}
}
onMessageArrived (message) {
// const msg = JSON.parse(message.payloadString);
this.callBack && this.callBack(typeof msg === 'string' ? message : JSON.parse(message))
}
}
在main.js中引入mqtt.js
import myMqtt from './mqtt.js'
之后再创建mqtt实例,订阅主题即可。
注意:
如果你的mqtt报
errorcode: 8
errorMessage: “AMQJS0008I Socket closed.”
那么90%是你的clientId冲突了,最简单的办法是把上述代码中的protocolId改为“”,这样mqtt会自动分配clientId。最好的办法还是给protocolId设置一个动态值。