vue3+ts 封装mqtt
在Vue 3和TypeScript中封装MQTT客户端,你可以创建一个可复用的组件或者一个服务。以下是一个简单的封装示例,使用了mqtt
包。
首先,安装mqtt
包:
npm install mqtt
然后,创建一个封装MQTT的类:
// mqttClient.ts
import mqtt from 'mqtt';
export default class MqttClient {
private client: mqtt.Client;
constructor(private url: string, private options: mqtt.IClientOptions) {
this.client = mqtt.connect(url, options);
}
public publish(topic: string, message: string): void {
this.client.publish(topic, message);
}
public subscribe(topic: string, callback: mqtt.MessageCallback): void {
this.client.subscribe(topic, (error, granted) => {
if (error) {
console.error(error);
} else {
console.log('Subscribed to:', granted);
}
});
this.client.on(topic, callback);
}
public unsubscribe(topic: string): void {
this.client.unsubscribe(topic, (error) => {
if (error) {
console.error(error);
} else {
console.log('Unsubscribed from:', topic);
}
});
}
public end(): void {
this.client.end();
}
}
使用该类创建MQTT客户端实例并管理订阅:
// main.ts
import MqttClient from './mqttClient';
const url = 'ws://broker.hivemq.com:8000/ws';
const options = {
clientId: 'myClientId',
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
will: {
topic: 'WillTopic',
payload: 'ConnectionClosedUnexpectedly',
qos: 0,
retain: false,
},
username: 'yourUsername',
password: 'yourPassword',
keepalive: 60,
};
const mqttClient = new MqttClient(url, options);
mqttClient.subscribe('myTopic', (message) => {
console.log('Received message on myTopic:', message.toString());
});
// 发布消息
mqttClient.publish('myTopic', 'Hello MQTT');
// 结束连接
mqttClient.end();
这个简单的封装提供了发布消息、订阅和取消订阅的方法。在实例化MqttClient
时,你需要提供MQTT服务器的URL和选项。在订阅回调中,你可以处理接收到的消息。记得在结束使用后调用end()
方法来关闭MQTT连接。
评论已关闭