在VUE中利用MQTT协议实现即时通讯

11次阅读

共计 1252 个字符,预计需要花费 4 分钟才能阅读完成。

前言
建议先阅读:在 Node.js 下运用 MQTT 协议实现即时通讯及离线推送
以前尝试在 vue 中用上 mqtt,了解到 mqtt 实质上是基于 websocket 进行数据通信,所以上文中在 node 下实现的服务端此时不能满足需求
代码
服务端: server.js
let http = require(‘http’)
, httpServer = http.createServer()
, mosca = require(‘mosca’)

let settings = {
port: 5112,
persistence:{
factory: mosca.persistence.Mongo,
url: “mongodb://localhost:27017/mosca”
}
}
let server = new mosca.Server(settings)

server.attachHttpServer(httpServer)
server.on(‘published’, function(packet, client) {
console.log(‘Published’, packet.payload.toString());
})
httpServer.listen(3003)
server.on(‘ready’, function(){
console.log(‘server is running at port 3003’);
})
服务端 mosca 的实例化并没有改动而是将其为 websocket 形式进行适配
客户端: mqtt.js
let mqtt = require(‘mqtt’)
let client = {}
export default {
launch(id, callback) {
client = mqtt(‘mqtt://ip’, {
port: 3003,
clientId: id,
clean: false
})
client.on(‘message’, (topic, message) => {
callback(topic, message)
})
},
end() {
client.end()
},
subscribe(topic) {
client.subscribe(topic, {qos: 1})
console.log(‘subscribe:’, topic)
},
publish(topic, message) {
client.publish(topic, JSON.stringify(message), {qos: 1})
}
}
独立地对 mqtt 进行简单地封装,方便调用值得注意的是此时的协议头仍为 mqtt,但 mqtt 源码会以 ws 形式进行通信
main.js: 再把 mqtt 绑到 vue 原型链上
import mqtt from ‘./api/mqtt’
Vue.prototype.$mqtt = mqtt

现在便可在 vue 环境中对 mqtt 进行调用
this.$mqtt.launch(this.user._id, (topic, source) => {
console.log(‘message: ‘, JSON.parse(source.toString()))
})
转载请注明出处 ; )

正文完
 0