Vue 是一款由尤雨溪及其團隊開發的漸進式 Javascript 前端框架。該框架具備數據雙向綁定、組件化、響應式和輕量等特點,搭配其腳手架 Vue CLI 使得開發者更加容易上手,大大減少了學習成本。同時其配備一個專用的狀態管理模式 Vuex ,在這里可以集中管理所有組件的狀態。
MQTT 是一種基於發布/訂閱模式的 輕量級物聯網消息傳輸協議。該協議提供了一對多的消息分發和應用程序的解耦,具備很小的傳輸消耗和協議數據交換、最大限度減少網絡流量和三種不同消息服務質量等級,滿足不同投遞需求的優勢。
本文主要介紹如何在 Vue 項目中使用 MQTT,實現客戶端與 MQTT 服務器的連接、訂閱、收發消息、取消訂閱等功能。
項目初始化
新建項目
參考鏈接如下:
使用 Vue CLI 創建 Vue 項目
通過引用 Vue.js 創建 Vue 項目
示例:
1 vue create vue-mqtt-test
安裝 MQTT 客戶端庫
-
通過命令行安裝:可以使用 npm 或 yarn 命令,二者選一
1 npm install mqtt --save
1 yarn add mqtt
- 通過 CDN 引入
1 <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
- 下載到本地,然后使用相對路徑引入
1 <script src="/your/path/to/mqtt.min.js"></script>
MQTT 的使用
連接 MQTT 服務器
本文將使用 EMQ X 提供的 免費公共 MQTT 服務器,該服務基於 EMQ X 的 MQTT 物聯網雲平台 創建。服務器接入信息如下:
Broker: broker.emqx.io
TCP Port: 1883
Websocket Port: 8083
連接關鍵代碼:
1 <script> 2 import mqtt from 'mqtt' 3 4 export default { 5 data() { 6 return { 7 connection: { 8 host: 'broker.emqx.io', 9 port: 8083, 10 endpoint: '/mqtt', 11 clean: true, // 保留會話 12 connectTimeout: 4000, // 超時時間 13 reconnectPeriod: 4000, // 重連時間間隔 14 // 認證信息 15 clientId: 'mqttjs_3be2c321', 16 username: 'emqx_test', 17 password: 'emqx_test', 18 }, 19 subscription: { 20 topic: 'topic/mqttx', 21 qos: 0, 22 }, 23 publish: { 24 topic: 'topic/browser', 25 qos: 0, 26 payload: '{ "msg": "Hello, I am browser." }', 27 }, 28 receiveNews: '', 29 qosList: [ 30 { label: 0, value: 0 }, 31 { label: 1, value: 1 }, 32 { label: 2, value: 2 }, 33 ], 34 client: { 35 connected: false, 36 }, 37 subscribeSuccess: false, 38 } 39 }, 40 41 methods: { 42 // 創建連接 43 createConnection() { 44 // 連接字符串, 通過協議指定使用的連接方式 45 // ws 未加密 WebSocket 連接 46 // wss 加密 WebSocket 連接 47 // mqtt 未加密 TCP 連接 48 // mqtts 加密 TCP 連接 49 // wxs 微信小程序連接 50 // alis 支付寶小程序連接 51 const { host, port, endpoint, ...options } = this.connection 52 const connectUrl = `ws://${host}:${port}${endpoint}` 53 try { 54 this.client = mqtt.connect(connectUrl, options) 55 } catch (error) { 56 console.log('mqtt.connect error', error) 57 } 58 this.client.on('connect', () => { 59 console.log('Connection succeeded!') 60 }) 61 this.client.on('error', error => { 62 console.log('Connection failed', error)ß 63 }) 64 this.client.on('message', (topic, message) => { 65 this.receiveNews = this.receiveNews.concat(message) 66 console.log(`Received message ${message} from topic ${topic}`) 67 }) 68 }, 69 } 70 } 71 </script>
訂閱主題
1 doSubscribe() { 2 const { topic, qos } = this.subscription 3 this.client.subscribe(topic, qos, (error, res) => { 4 if (error) { 5 console.log('Subscribe to topics error', error) 6 return 7 } 8 this.subscribeSuccess = true 9 console.log('Subscribe to topics res', res) 10 }) 11 },
取消訂閱
1 doUnSubscribe() { 2 const { topic } = this.subscription 3 this.client.unsubscribe(topic, error => { 4 if (error) { 5 console.log('Unsubscribe error', error) 6 } 7 }) 8 }
消息發布
1 doPublish() { 2 const { topic, qos, payload } = this.publication 3 this.client.publish(topic, payload, qos, error => { 4 if (error) { 5 console.log('Publish error', error) 6 } 7 }) 8 }
斷開連接
1 destroyConnection() { 2 if (this.client.connected) { 3 try { 4 this.client.end() 5 this.client = { 6 connected: false, 7 } 8 console.log('Successfully disconnected!') 9 } catch (error) { 10 console.log('Disconnect failed', error.toString()) 11 } 12 } 13 }
總結
綜上所述,我們實現了在 Vue 項目中創建 MQTT 連接,模擬了客戶端與 MQTT 服務器進行訂閱、收發消息、取消訂閱以及斷開連接的場景。
Vue 作為三大主流的前端框架之一,既能夠在瀏覽器端使用,也能夠在移動端使用,結合 MQTT 協議及 MQTT 物聯網雲服務 可以開發出很多有趣的應用,比如客服聊天系統或實時監控物聯網設備信息的管理系統。
————————————————
版權聲明:本文為CSDN博主「EMQX」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/emqx_broker/article/details/108769925