1、安装依赖
npm install mqtt -S
2、组件内引用
import mqtt from 'mqtt'
3、定义data
connection:{
//连接信息
host: 'localhost',
port: 8083,
endpoint: '/mqtt',
clean: true, // 保留回话
connectTimeout: 4000, // 超时时间
reconnectPeriod: 4000, // 重连时间间隔
//clientId,这个是EMQ Dashboard的上的clientId 对应就好
// clientId: 'emq2',
clientId: 'emq2',
username: 'xxxxx',
password: 'ccccc',
},
mqttClient:null,//mqtt连接对象
4、订阅连接
createMqttConnect(){
//创建连接MQTT
const { host, port, endpoint, ...options } = this.connection
const connectUrl = `ws://${host}:${port}${endpoint}`
this.mqttClient=mqtt.connect(connectUrl, this.options) //建立连接
this.mqttClient.on('connect', (res) => {
console.log('连接成功')
// 这儿直接获取订阅的主题就好了
this.mqttClient.subscribe('testtopic', {
qos: 1 // 这儿直接EMQ的qos对应的就好了
}, (res) => {
if (!res) {
console.log('订阅成功');
} else {
console.log('订阅失败');
}
})
})
},
closeMqtt(){
//MQTT关闭连接
this.mqttClient.end()
},
mqttTest(){
//测试MQTT订阅
this.createMqttConnect()
this.mqttClient.on('message', (topic, message) => {
console.log('收到来自', topic, '的消息', message.toString())
})
},
5、常用端口
1883 MQTT TCP 协议端口
8883 MQTT/TCP SSL 端口
8083 MQTT/WebSocket 端口
8084 MQTT/WebSocket with SSL 端口
8080 MQTT执行引擎HTTP API 端口
18083 EMQX Dashboard 管理控制台端口