在VUE中利用MQTT協議實現即時通信

前言

建議先閱讀:
在Node.js下運用MQTT協議實現即時通信及離線推送vue

之前嘗試在vue中用上mqtt,瞭解到mqtt實質上是基於websocket進行數據通訊,因此上文中在node下實現的服務端此時不能知足需求node

代碼

服務端: server.jsweb

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的實例化相較於在Node中的實現並無改動
而是將其爲websocket形式進行適配mongodb

客戶端: mqtt.jssegmentfault

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形式進行通訊api

main.js:
再把mqtt綁到vue原型鏈上websocket

import mqtt from './api/mqtt'
Vue.prototype.$mqtt = mqtt

如今即可在vue環境中對mqtt進行調用socket

this.$mqtt.launch(this.user._id, (topic, source) => {
    console.log('message: ', JSON.parse(source.toString()))
})

轉載請註明出處 ; )ui

相關文章
相關標籤/搜索