赞
踩
TIPS:以下实例不对uniapp做过多的阐述
// export const MQTT_IP = '192.168.1.173:8083/mqtt'
export const MQTT_IP = 'localhost:8083/mqtt'
const MQTT_USERNAME = 'admin'
const MQTT_PASSWORD = 'public'
export const MQTT_OPTIONS = {
connectTimeout: 5000,
clientId: '',
username: MQTT_USERNAME,
password: MQTT_PASSWORD,
clean: false
}
main.vue:
<script>
import {
v4
} from 'uuid' //mqtt里面的clientId用uuid生成唯一标识符,防止不同页面订阅主题时出现数据粘连
import {
MQTT_IP,
MQTT_OPTIONS
} from '@/util/mqtt.js'
var mqtt = require('mqtt/dist/mqtt.js')
var client;
export default {
data() {
return {
topic: 'M3',
sendTopic: 'setM3'
};
},
mounted() {
this.connect()
},
methods: {
//发布消息接口
sendPublish(data) {
console.log('发布:', data)
//生成访问mqtt的用户id
MQTT_OPTIONS.clientId = v4()
client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
client.on('connect', () => {
console.log("connnect success!")
client.publish(this.sendTopic, JSON.stringify(data), {
qos: 1
})
}).on('error', (err) => {
console.log(err)
client.end()
})
},
//订阅接口
connect() {
MQTT_OPTIONS.clientId = v4()
client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
client.on('connect', () => {
console.log('连接成功!')
client.subscribe(this.topic, (err) => {
if (!err) {
console.log('订阅成功!')
}
}).on('reconnect', (err) => {
console.log('正在重连...' + this.topic)
}).on('end', (err) => {
console.log('连接断开!')
}).on('message', (topic, message) => {
try {
let data = JSON.parse(message)
console.log('接收推送信息:', data)
} catch (e) {
console.log("Caught: " + e.message)
}
})
})
}
}
}
</script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。