Vue 是一款由尤雨溪及其團隊開發的漸進式 Javascript 前端框架。該框架具備數據雙向綁定、組件化、響應式和輕量等特點,搭配其腳手架 Vue CLI 使得開發者更加容易上手,大大減少了學習成本。同時其配備一個專用的狀態管理模式 Vuex ,在這里可以集中管理所有組件的狀態。
MQTT 是一種基於發布/訂閱模式的 輕量級物聯網消息傳輸協議。該協議提供了一對多的消息分發和應用程序的解耦,具備很小的傳輸消耗和協議數據交換、最大限度減少網絡流量和三種不同消息服務質量等級,滿足不同投遞需求的優勢。
本文主要介紹如何在 Vue 項目中使用 MQTT,實現客戶端與 MQTT 服務器的連接、訂閱、收發消息、取消訂閱等功能。
項目初始化
新建項目
參考鏈接如下:
示例:
vue create vue-mqtt-test
安裝 MQTT 客戶端庫
-
通過命令行安裝:
可以使用 npm 或 yarn 命令,二者選一
-
npm install mqtt --save
-
yarn add mqtt
-
通過 CDN 引入
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
-
下載到本地,然后使用相對路徑引入
<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
連接關鍵代碼:
<script>
import mqtt from 'mqtt'
export default {
data() {
return {
connection: {
host: 'broker.emqx.io',
port: 8083,
endpoint: '/mqtt',
clean: true, // 保留會話
connectTimeout: 4000, // 超時時間
reconnectPeriod: 4000, // 重連時間間隔
// 認證信息
clientId: 'mqttjs_3be2c321',
username: 'emqx_test',
password: 'emqx_test',
},
subscription: {
topic: 'topic/mqttx',
qos: 0,
},
publish: {
topic: 'topic/browser',
qos: 0,
payload: '{ "msg": "Hello, I am browser." }',
},
receiveNews: '',
qosList: [
{ label: 0, value: 0 },
{ label: 1, value: 1 },
{ label: 2, value: 2 },
],
client: {
connected: false,
},
subscribeSuccess: false,
}
},
methods: {
// 創建連接
createConnection() {
// 連接字符串, 通過協議指定使用的連接方式
// ws 未加密 WebSocket 連接
// wss 加密 WebSocket 連接
// mqtt 未加密 TCP 連接
// mqtts 加密 TCP 連接
// wxs 微信小程序連接
// alis 支付寶小程序連接
const { host, port, endpoint, ...options } = this.connection
const connectUrl = `ws://${host}:${port}${endpoint}`
try {
this.client = mqtt.connect(connectUrl, options)
} catch (error) {
console.log('mqtt.connect error', error)
}
this.client.on('connect', () => {
console.log('Connection succeeded!')
})
this.client.on('error', error => {
console.log('Connection failed', error)ß
})
this.client.on('message', (topic, message) => {
this.receiveNews = this.receiveNews.concat(message)
console.log(`Received message ${message} from topic ${topic}`)
})
},
}
}
</script>
訂閱主題
doSubscribe() {
const { topic, qos } = this.subscription
this.client.subscribe(topic, qos, (error, res) => {
if (error) {
console.log('Subscribe to topics error', error)
return
}
this.subscribeSuccess = true
console.log('Subscribe to topics res', res)
})
},
取消訂閱
doUnSubscribe() {
const { topic } = this.subscription
this.client.unsubscribe(topic, error => {
if (error) {
console.log('Unsubscribe error', error)
}
})
}
消息發布
doPublish() {
const { topic, qos, payload } = this.publication
this.client.publish(topic, payload, qos, error => {
if (error) {
console.log('Publish error', error)
}
})
}
斷開連接
destroyConnection() {
if (this.client.connected) {
try {
this.client.end()
this.client = {
connected: false,
}
console.log('Successfully disconnected!')
} catch (error) {
console.log('Disconnect failed', error.toString())
}
}
}
測試
我們使用 Vue 編寫了如下簡單的瀏覽器應用,該應用具備:創建連接、訂閱主題、收發消息、取消訂閱、斷開連接等功能。
項目完整代碼請見:https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-Vue.js。
使用 MQTT 5.0 客戶端工具 - MQTT X 作為另一個客戶端進行消息收發測試。
在 MQTT X 發送第二條消息之前,在瀏覽器端進行取消訂閱操作,瀏覽器端將不會收到 MQTT X 發送的后續消息。
總結
綜上所述,我們實現了在 Vue 項目中創建 MQTT 連接,模擬了客戶端與 MQTT 服務器進行訂閱、收發消息、取消訂閱以及斷開連接的場景。
Vue 作為三大主流的前端框架之一,既能夠在瀏覽器端使用,也能夠在移動端使用,結合 MQTT 協議及 MQTT 物聯網雲服務 可以開發出很多有趣的應用,比如客服聊天系統或實時監控物聯網設備信息的管理系統。
版權聲明: 本文為 EMQ 原創,轉載請注明出處。