子沫
uniapp连接mqtt进行消息的订阅与发布
11/10
本文最后更新于2022年11月10日,已超过741天没有更新。如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!
- 先安装Mqtt包,到你项目中的 node_modules目录下执行一下安装命令
npm install mqtt --save
- 创建一个配置文件js,建议放到utils目录下 mqtt.js
export const MQTT_IP = ''//mqtt地址端口, 使用emqx时一定要加mqtt
const MQTT_USERNAME = ''//mqtt用户名
const MQTT_PASSWORD = ''//密码
export const MQTT_OPTIONS = {
connectTimeout: 5000,
clientId: '',
username: MQTT_USERNAME,
password: MQTT_PASSWORD,
clean: false,
keepalive: 15,
protocolVersion: 4, //MQTT连接协议版本
resubscribe: true,
reconnectPeriod: 1000,
}
- 在common中定义一个公用的mqtt.js各个需要使用的地方调用即可
// "use strict";
// Object.defineProperty(exports, "__esModule", {
// value: !0
// });
import { v4 } from 'uuid';
import {
MQTT_IP,
MQTT_OPTIONS
} from '@/utils/mqtt.js';
var mqtt = require('mqtt/dist/mqtt.js')
var client;
var topic=[
'online',
'movie',
'update',
'notice'
];
var init=function(){
let userInfos = uni.getStorageSync('userInfo');
console.log('用户信息:'+userInfos)
MQTT_OPTIONS.clientId =userInfos !=""?userInfos.mobile+'':v4();
// #ifdef H5
client = mqtt.connect('ws://' + MQTT_IP, MQTT_OPTIONS)
// #endif
// #ifdef MP-WEIXIN||APP-PLUS
client = mqtt.connect('wx://' + MQTT_IP, MQTT_OPTIONS)
// #endif
client.on('connect', function() {
console.log('连接成功')
for (var i = 0; i < topic.length; i++){
client.subscribe(topic[i], function(err) {
if (!err) {
console.log('订阅成功')
}
})
}
}).on('reconnect', function(error) {
console.log('正在重连...')
subscribeTopic();
}).on('error', function(error) {
console.log('连接失败...', error)
}).on('end', function() {
console.log('连接断开')
}).on('message', function(topic, message) {
console.log('接收推送信息:', message.toString());
doSomeThing(topic,JSON.parse(message.toString()));
}).on('close',function(re){
console.log('链接关闭')
})
},
sendMessage=function(t,str){
client.publish(t, str, (e) => {
console.log(e)
})
},
doSomeThing=function(t,str){
console.log('接收到的Topic:'+t)
switch (t){
case 'update':
break;
case 'movie':
plus.push.createMessage(str.title, {}, {} );
plus.push.addEventListener('click',msg=> {
uni.navigateTo({
url:"/pages/detail/index?id="+str.vid
})
});
break;
case 'online':
break;
case 'notice':
break;
default:
break;
}
},
subscribeTopic=function(){
for (var i = 0; i < topic.length; i++){
client.subscribe(topic[i], function(err) {
if (!err) {
console.log('订阅成功')
}
})
}
};
export default {
init: init,
sendMessage: sendMessage,
subscribeTopic: subscribeTopic,
doSomeThing:doSomeThing
};
- 到main.js中定义mqttClient
import mqttClient from '@/common/mqtt';
Vue.prototype.$mqtt = mqttClient;
- 具体mqtt的使用
var s=e.device.deviceBrand; this.$mqtt.sendMessage('online','{"type":"upMB","brand":"'+s+'"}');// 进行线上的Topic发布
版权属于:
Strjson博客-专注于各种精品源码、精品软件、技术教程分享、黑客技术、破解教程(爱你在心口难开、没事写一写)
本文链接:
https://jpgke.com/jiaocheng/413.html(转载时请注明本文出处及文章链接)
作品采用: