使用uniapp开发小程序接入mqtt

uniapp开发小程序和h5中接入mqtt

下载mqtt依赖包

在这里插入图片描述

  • 安装:打开项目终端,运行npm install mqtt@4.1.0
    安装好以后在项目的node_modules可以看到mqtt文件夹,而且在package.json里面看到对应的mqtt版本
  • 注意:假如不小心安装了其他版本的包请卸载 npm uninstall mqtt@x.x.xx;本人测试只有4.1.0版本,h5和小程序兼容性最好

封装一个mqttUtils.js

  • 创建好js文件以后引入mqtt:import mqtt from ‘mqtt/dist/mqtt.min.js’;必须是mqtt.min.js,不然微信小程序肯定报错;
  • H5和微信小程序的socket域名不一样,请注意wss和wxs(需要证书)
import mqtt from 'mqtt/dist/mqtt.min.js';

class mqttUtils {
	constructor({
		clientId
	}) {
		// #ifdef H5
		this.url =
			 'wss://xxx.xxxxxx.com:8888/ws?satoken=xxx'; 
		// #endif

		// #ifdef MP-WEIXIN
		this.url =
			 'wxs://xxx.xxxxxx.com:8888/ws?satoken=xxx'; 
		// #endif
		this.clientId = clientId;;
		this.client = null;
	}

	// 初始化
	init() {
		const options = {
			clean:false, 
			clientId: this.clientId,
			username: "你的用户名" 
			password: "你的密码", 
			connectTimeout: 12000, 
			keepalive: 60, 
		};
		this.client = mqtt.connect(this.url, options);
		this.client.on('connect', () => {
			//连接成功
		});
		this.client.on('error', (error) => {
			//连接错误
		});
		this.client.on('reconnect', (error) => {
			//重新连接失败
		});
	}

	// 订阅消息渠道
	subscribeMessage(topic) {
		this.client.subscribe(topic, (error) => {
			if (!error) {
				//订阅成功
			} else {
				//订阅失败
			}
		});
	}

	// 取消订阅渠道
	unsubscribeMessage(topic) {
		this.client.unsubscribe(topic, (error) => {
			if (!error) {
				//取消成功
			} else {
				//取消失败
			}
		});
	}

	// 接收mqtt消息
	getMessage(callback) {
		this.client.on('message', callback);
	}

	// 销毁mqtt
		overMqtt() {
		if (this.client) {
			this.client.end();
			//销毁mqtt
		}

	}
}

export default mqttUtils;

使用

  • 你可以放在全局使用,也可以在一个页面使用,看你的业务场景吧
    import mqttUtils from “@/utils/mqttUtils.js”

  • 初始化mqtt

//初始化mqtt
				this.mqttClient = new mqttUtils({
					clientId: "wx_" + uuid;(创建的时候可以是随机数,可以用uuid生成一个,看你喜欢怎么干)
				});
				this.mqttClient.init();	
				this.mqttClient.subscribeMessage('mqtt-一个约定好的渠道');//订阅消息渠道-字母字母字母
				this.mqttClient.getMessage((topic, message) => {
					console.log(`收到来自的消息:`, JSON.parse(message.toString()));//收到的消息可以打印出来看看
				});
  • 销毁mqtt,在适当的位置干掉
this.mqttClient.unsubscribeMessage('mqtt-一个约定好的渠道');//订阅消息渠道-字母字母字母
this.mqttClient.overMqtt();
  • 微信开发工具中打印可以看到
    在这里插入图片描述

总结

刚开始还是挺头大的,但是配置好能发消息能接受消息,也感叹原来如此!有些小细节一定要注意,不然找问题能找半天,肯定没问题;这个方法其实也支持前端,但是要引入的时候要注意是mqtt.js!!!

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值