vue3中如何使用mqtt數(shù)據(jù)傳輸
使用版本
"mqtt": "^5.8.0",
安裝指令
npm install mqtt --save ------ yarn add mqtt
配置
connection: {
protocol: "ws",
host: "broker.emqx.io",
port: 8083,
endpoint: "/mqtt",
clean: true,
connectTimeout: 30 * 1000, // ms
reconnectPeriod: 4000, // ms
clientId: "emqx_vue_" + Math.random().toString(16).substring(2, 8),
// 隨機(jī)數(shù) 每次不能重復(fù)
username: "emqx_test",
password: "emqx_test",
},
連接
import mqtt from "mqtt";
let client = {}
client = mqtt.connect(url, options)
client.on('connect', (e) => {
// 訂閱主題
})
訂閱主題
client.subscribe(topic, { qos: 1 }, (err) => {
if (!err) {
console.log('訂閱成功')
} else {
console.log('消息訂閱失??!')
}
})
消息發(fā)布
給后端發(fā)送格式,是和后端約定好的數(shù)據(jù)格式,一般為JSON傳輸。
client.publish(publishTopic, `{"messageType":1,"messageContent":""}`, { qos: 0 }, (err) => {
if (!err) {
console.log('發(fā)送成功')
client.subscribe(topic, { qos: 1 }, (err) => {
if (!err) {
console.log('訂閱成功')
} else {
console.log('消息訂閱失?。?)
}
})
} else {
console.log('消息發(fā)送失?。?)
}
})
取消訂閱
client.unsubscribe(topicList, (error) => {
console.log('主題為' + topicList + '取消訂閱成功', error)
})
斷開連接
export function unconnect() {
client.end()
client = null
// Message.warning('服務(wù)器已斷開連接!')
console.log('服務(wù)器已斷開連接!')
}
mqtt封裝使用(ts版)
import type { IClientOptions, MqttClient } from 'mqtt';
import mqtt from 'mqtt';
interface ClientOptions extends IClientOptions {
clientId: string;
}
interface SubscribeOptions {
topic: string;
callback: (topic: string, message: string) => void;
subscribeOption?: mqtt.IClientSubscribeOptions;
}
interface PublishOptions {
topic: string;
message: string;
}
class Mqtt {
private static instance: Mqtt;
private client: MqttClient | undefined;
private subscribeMembers: Record<string, ((topic: string, message: string) => void) | undefined> = {};
private pendingSubscriptions: SubscribeOptions[] = [];
private pendingPublications: PublishOptions[] = [];
private isConnected: boolean = false;
private constructor(url?: string) {
if (url) {
this.connect(url);
}
}
public static getInstance(url?: string): Mqtt {
if (!Mqtt.instance) {
Mqtt.instance = new Mqtt(url);
} else if (url && !Mqtt.instance.client) {
Mqtt.instance.connect(url);
}
return Mqtt.instance;
}
private connect(url: string): void {
console.log(url, clientOptions);
if (!this.client) {
this.client = mqtt.connect(url, clientOptions);
this.client.on('connect', this.onConnect);
this.client.on('reconnect', this.onReconnect);
this.client.on('error', this.onError);
this.client.on('message', this.onMessage);
}
}
public disconnect(): void {
if (this.client) {
this.client.end();
this.client = undefined;
this.subscribeMembers = {};
this.isConnected = false;
console.log(`服務(wù)器已斷開連接!`);
}
}
public subscribe({ topic, callback }: SubscribeOptions): void {
if (this.isConnected) {
this.client?.subscribe(topic, { qos: 1 }, error => {
if (error) {
console.log(`客戶端: ${clientOptions.clientId}, 訂閱主題: ${topic}失敗: `, error);
} else {
console.log(`客戶端: ${clientOptions.clientId}, 訂閱主題: ${topic}成功`);
}
});
this.subscribeMembers[topic] = callback;
} else {
this.pendingSubscriptions.push({ topic, callback });
}
}
public unsubscribe(topic: string): void {
if (!this.client) {
return;
}
this.client.unsubscribe(topic, error => {
if (error) {
console.log(`客戶端: ${clientOptions.clientId}, 取消訂閱主題: ${topic}失敗: `, error);
} else {
console.log(`客戶端: ${clientOptions.clientId}, 取消訂閱主題: ${topic}成功`);
}
});
this.subscribeMembers[topic] = undefined;
}
public publish({ topic, message }: PublishOptions): void {
if (this.isConnected) {
this.client?.publish(topic, message, { qos: 1 }, e => {
if (e) {
console.log(`客戶端: ${clientOptions.clientId}, 發(fā)送主題為: ${topic} 的消息, 發(fā)送失敗: `, e);
}
});
} else {
this.pendingPublications.push({ topic, message });
}
}
private onConnect = (e: any): void => {
console.log(`客戶端: ${clientOptions.clientId}, 連接服務(wù)器成功:`, e);
this.isConnected = true;
this.processPendingSubscriptions();
this.processPendingPublications();
};
private onReconnect = (): void => {
console.log(`客戶端: ${clientOptions.clientId}, 正在重連:`);
this.isConnected = false;
};
private onError = (error: Error): void => {
console.log(`客戶端: ${clientOptions.clientId}, 連接失敗:`, error);
this.isConnected = false;
};
private onMessage = (topic: string, message: Buffer): void => {
// console.log(
// `客戶端: ${clientOptions.clientId}, 接收到來自主題: ${topic} 的消息: `,
// message.toString(),
// );
const callback = this.subscribeMembers?.[topic];
callback?.(topic, message.toString());
};
private processPendingSubscriptions(): void {
while (this.pendingSubscriptions.length > 0) {
const { topic, callback, subscribeOption } = this.pendingSubscriptions.shift()!;
this.subscribe({ topic, callback, subscribeOption });
}
}
private processPendingPublications(): void {
while (this.pendingPublications.length > 0) {
const { topic, message } = this.pendingPublications.shift()!;
this.publish({ topic, message });
}
}
}
const clientOptions: ClientOptions = {
clean: true,
connectTimeout: 500,
protocolVersion: 5,
rejectUnauthorized: false,
username: 'admin',
password: 'Anjian-emqx',
clientId: `client-${Date.now()}`
};
// export default Mqtt.getInstance("ws://192.168.11.14:8083/mqtt");
// export default Mqtt.getInstance("ws://192.168.11.14:8083/mqtt");
// export default Mqtt.getInstance(JSON.parse(import.meta.env.VITE_OTHER_SERVICE_BASE_URL).mqtt);
const { protocol, host } = window.location;
export default Mqtt.getInstance(`${protocol.replace('http', 'ws')}//${host.replace('localhost', '127.0.0.1')}/mqtt/`);
注意:
1.環(huán)境配置
.env.test
VITE_OTHER_SERVICE_BASE_URL= `{
"mqtt": "ws://192.168.11.14:8083/mqtt"
}`
2.qos設(shè)置 前后端統(tǒng)一為1

以上就是vue3中如何使用mqtt數(shù)據(jù)傳輸?shù)脑敿?xì)內(nèi)容,更多關(guān)于vue3 mqtt數(shù)據(jù)傳輸?shù)馁Y料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue2封裝webSocket的實(shí)現(xiàn)(開箱即用)
在Vue2中,可以使用WebSocket實(shí)時通信,本文主要介紹了vue2封裝webSocket的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
關(guān)于Vue3路由push跳轉(zhuǎn)問題(解決Vue2this.$router.push失效)
這篇文章主要介紹了Vue3路由push跳轉(zhuǎn)問題(解決Vue2this.$router.push失效),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
Vue3處理錯誤邊界(error boundaries)的示例代碼
在開發(fā) Vue 3 應(yīng)用時,處理錯誤邊界(Error Boundaries)是一個重要的考量,在 Vue 3 中實(shí)現(xiàn)錯誤邊界的方式與 React 等其他框架有所不同,下面,我們將深入探討 Vue 3 中如何實(shí)現(xiàn)錯誤邊界,并提供一些示例代碼幫助理解什么是錯誤邊界,需要的朋友可以參考下2024-10-10
Vue Echarts渲染數(shù)據(jù)導(dǎo)致殘留臟數(shù)據(jù)的問題處理
這篇文章主要介紹了Vue Echarts渲染數(shù)據(jù)導(dǎo)致殘留臟數(shù)據(jù)的問題處理,文中通過代碼示例給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-08-08
Vue使用Props實(shí)現(xiàn)組件數(shù)據(jù)交互的示例代碼
在Vue中,組件的props屬性用于定義組件可以接收的外部數(shù)據(jù),這些數(shù)據(jù)來自父組件并傳遞給子組件,本文給大家介紹了Vue使用Props實(shí)現(xiàn)組件數(shù)據(jù)交互,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-06-06
Vue+Element一步步實(shí)現(xiàn)動態(tài)添加Input_輸入框案例
這篇文章主要介紹了Vue+Element一步步實(shí)現(xiàn)動態(tài)添加Input_輸入框案例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
一次在vue中使用post進(jìn)行excel表下載的實(shí)戰(zhàn)記錄
最近遇到了需求,覺著有必要給大家總結(jié)下,這篇文章主要給大家介紹了關(guān)于一次在vue中使用post進(jìn)行excel表下載的實(shí)戰(zhàn)記錄,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07

