MQTT 发布订阅模式简述网址:https://www.cnblogs.com/emqx/p/11799138.html
MQTT Broker 的连接使用 EMQ 提供的线上版 Websocket 工具:http://tools.emqx.io
操作步骤
1、填写基础信息

2、编辑基本信息,同时对照信息创建连接

3、发送消息时订阅通配符主题

4、完整代码
安装mqtt库
npm install mqtt --save
<template>
<div id="app">
<p>mqtt收到的数据:</p>
<p>{{this.msg}}</p>
<a-button @click="doPublish">发布</a-button>
</div>
</template>
<script>
import mqtt from 'mqtt'
export default {
data() {
return {
msg: '--',
connection:{
host: 'broker.emqx.io',
port: 8083,
endpoint: 'mqtt',
},
options:{
connectTimeout: 40000,
clientId: 'mqttx_6c65c4df',//认证消息
username: '',
password: '',
clean: true
},
client: {
connected: false,
},
publish: {
topic: 'testtopic/cc',
qos: 0
},
}
},
created() {
this.createConnection()
},
methods: {
// 创建连接
createConnection(){
this.client = mqtt.connect(`ws://${this.connection.host}:${this.connection.port}/${this.connection.endpoint}`, this.options)
this.client.on('connect', () => {
console.log("连接成功!!!")
this.client.subscribe(this.publish.topic, { qos: this.publish.qos }, (error) => {
if (!error) {
console.log('订阅成功')
} else {
console.log('订阅失败')
}
})
})
// 接收消息处理
this.client.on('message', (topic, message) => {
console.log('收到来自', topic, '的消息', message.toString())
this.msg = message.toString()
})
},
// 发布消息
doPublish() {
this.client.publish(this.publish.topic, this.publish.qos,this.msg);
}
}
}
</script>
<style scoped>
</style>