赞
踩
效果图
以下代码使用mqtt兼容H5、App、微信小程序、支付宝小程序
1.H5和App、微信小程序,统一使用依赖包的mqtt文件
npm i mqtt@3.0.0
2.支付宝小程序,需要在官网下载mqtt.min.js文件,存放路径:/utils/mqtt.min.js
下载js文件链接: https://pan.baidu.com/s/1KHE7FRa_GGQE0DM1U4pjcQ?pwd=5xuy
参考文档:快速使用MQTT 支付宝小程序 SDK实现消息收发 [IM 开发文档]
参考github代码:GitHub - Wster11/zhifubao-mqtt-demo
/utils/sendMqtt.js
- // #ifdef H5
- const mqtturl = "wss://";
- var mqtt = require('mqtt/dist/mqtt.js')
- // #endif
-
- // #ifdef APP-PLUS || MP-WEIXIN
- const mqtturl = "wxs://";
- var mqtt = require('mqtt/dist/mqtt.js')
- //#endif
-
- // #ifdef MP-ALIPAY
- const mqtturl = "alis://";
- var mqtt = require('@/utils/mqtt.min.js')
- // import mqtt from "@/utils/mqtt.min.js" // 或者这样引入
- //#endif
-
- var client;
-
- // 创建MQTT连接
- const createMqtt = () => {
- let options = {
- keepalive: 1, // 心跳时间最小值可以为0,表示客户端不断开。 假如设置为0 断开网络监听不到 手机应用缩小化mqtt掉线后 根据心跳时间重新请求连接mqtt
- clientId: "你的clientId",
- protocolId: 'MQTT',
- username: "你的username",
- password: "你的password",
- protocolVersion: 4,
- clean: true,
- reconnectPeriod: 1000, // reconnectPeriod为1000毫秒,这意味着在连接丢失之后,客户端将在1秒后尝试重新连接。
- connectTimeout: 5000, // 5s超时时间 意味着mqtt-reconnect函数5秒钟触发一次
- topic: "你的topic",
- rejectUnauthorized: false,
- // #ifdef MP-ALIPAY
- my: my,//注意这里的my
- //#endif
- }
-
- try {
- if (!client) {
- client = mqtt.connect("你的mqtturl", options);
- initEventHandleMqtt(options.topic);
- }
- } catch (e) {}
- };
-
- //建立连接
- const initEventHandleMqtt = (topicUrl) => {
- client.on("connect", function() {
- uni.hideLoading()
- console.log("mqtt连接成功");
- //订阅主题 presence
- client.subscribe(topicUrl, function(err) {
- console.log("mqtt订阅主题");
- });
- });
-
- //如果mqttws订阅主题成功,那么这里就是当接收到自己订阅主题的处理逻辑
- client.on("message", function(topic, message) {
- // 获取信息
- const mqttData = JSON.parse(message);
- // 传递信息
- uni.$emit("mqttData", mqttData);
- });
-
- // 重新连接
- client.on('reconnect', function() {
- uni.showLoading({
- title: "重新连接"
- })
- })
-
- //如果连接错误,打印错误
- client.on("error", function(err) {
- console.log('mqtt---error...', err)
- });
-
- // 断开连接
- client.on('disconnect', function() {})
-
- // 连接断开后触发的回调
- client.on("close", function() {});
-
- // 掉线
- client.on("offline", function() {});
-
- // 断开
- client.on('end', () => {});
- };
-
- //强制断开Mqtt
- const closeMqtt = () => {
- client?.end()
- client = null
- };
-
- // 使用心跳 判断客户端和服务端是否还在连接着
- const judgeBeat = () => {
- if (client && client.pingResp === false) {}
- }
-
- export {
- createMqtt,
- closeMqtt,
- client,
- }

接收到的数据,给页面赋值,实现实时更新页面数据
- <script>
- import {
- createMqtt
- } from '@/utils/sendMqtt.js';
-
- export default {
- onLoad() {
- createMqtt();
- },
- mounted() {
- // 接收Mqtt信息
- uni.$on('mqttData', (msgData) => {
- });
- },
- }
- </script>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。