vue中利用mqtt服務端實現即時通訊的步驟記錄
阿新 • • 發佈:2021-07-04
MQTT協議
MQTT(Message Queuing Telemetry Transport,訊息佇列遙測傳輸)是IBM開發的一個即時通訊協議,有可能成為物聯網的重要組成部分。該協議支援所有平臺,幾乎可以把所有聯網物品和外部連線起來,被用來當做感測器和制動器(比如通過Twitter讓房屋聯網)的通訊協議。
MQTT是輕量級基於代理的釋出/訂閱的訊息傳輸協議,它可以通過很少的程式碼和頻寬和遠端裝置連線。例如通過衛星和代理連線,通過撥號和醫療保健提供者連線,以及在一些自動化或小型裝置上,而且由於小巧,省電,協議開銷小和能高效的向一和多個接收者傳遞資訊,故同樣適用於稱動應用裝置上。
利用mqtt服務端實現即時通訊
在大部分專案中,前後端互動只是前端請求後端的介面,拿到資料後再處理,前段時間我手上的一個專案需要用到mqtt,使用後覺得真神奇,只需要訂閱就能實時獲取到資料,廢話不多說,妹妹給你們上步驟!
1.在vue專案中安裝mqtt.
npm install mqtt --save
2.在專案的main.js或者在需要用到的vue頁面上引用
import mqtt from 'mqtt'
3.在vue頁面的data中定義一個client物件,方便後面使用
client: {}
ok,接下來就是重點了,首先我們得連線mqtt,連線mqtt的方法有個回撥函式,我接下來就把訂閱的方法寫在連線成功後的回撥裡,這樣能保證不出錯,上程式碼!
4.連線mqtt並訂閱
//連線伺服器 connect() { let options = { username: "xxx",password: "xxxx",cleanSession : false,keepAlive:60,clientId: 'mqttjs_' + Math.random().toString(16).substr(2,8),connectTimeout: 4000 } this.client = mqtt.connect('ws://192.168.xxx.xx:8083/mqtt',options); this.client.on("connect",(e)=>{ console.log("成功連線伺服器:",e); //訂閱三個名叫'top/#','three/#'和'#'的主題 this.client.subscribe(['top/#','three/#','#'],{ qos: 1 },(err)=> { if (!err) { console.log("訂閱成功"); www.cppcns.com//向主題叫“pubtop”釋出一則內容為'hello,this is a nice day!'的訊息 this.publihttp://www.cppcns.comsh("pubtop",'hello,this is a nice day!') } else { console.log('訊息訂閱失敗!') } }); }); //重新連線 this.reconnect() //是否已經斷開連線 this.mqttError() //監聽獲取資訊 this.getMessage() }
5.釋出訊息方法
//釋出訊息@topic主題 @message釋出內容
publish(topic,message) {
if (!this.client.cElNgflNXIWonnected) {
console.log('客戶端未連線')
return
}
this.client.publish(topic,message,{qos: 1},(err) => {
if(!err) {
console.log('主題為'+topic+ "釋出成功")
}
})
}
6.監聽並接收上面訂閱的三個主題的資訊
//監聽接收訊息 getMessage() { this.client.on("message",(topic,message) => { if(message) { console.log('收到來著',topic,'的資訊',message.toString()) const res = JSON.parse(message.toString()) //console.log(res,'rwww.cppcns.comes') switch(topic) { case 'top/#' : this.msg = res break; case 'three/#' : this.msg = res break; case 'three/#' : this.msg = res break; default: return this.msg = res } this.msg = message } }); },
7.監聽伺服器是否連線失敗
//監聽伺服器是否連線失敗 mqttError() { this.client.on('error',(error) => { console.log('連線失敗:',error) this.client.end() }) },
8.取消訂閱
//取消訂閱 unsubscribe() { this.client.unsubscribe(this.mtopic,(error)=> { console.log('主題為'+ this.mtopic+'取消訂閱成功',error) }) },
9.斷開連線
//斷開連線 unconnect() { this.client.end() this.client = null console.log('伺服器已斷開連線!') },
10.監聽伺服器重新連線
//監聽伺服器重新連線 reconnect() { this.client.on('reconnect',(error) => { console.log('正在重連:',error) }); },
總結
到此這篇關於vue中利用mqtt服務端實現即時通訊的文章就介紹到這了,更多相關vue用mqtt即時通訊內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!