小程序连接MQTT服务器,以及配置,避坑

1、MQTT服务器域名配置

由于小程序必须使用域名方式连接socket,所以必须为MQTT服务器配置域名,并配置SSL证书。

1.1相关文档:

EMQX 企业版安装 | EMQX 企业版 4.4 文档

EMQX MQTT 微信小程序接入 | EMQX 4.2 文档

MQTT 下载引入和配置连接 | ESP32全栈应用开发文档 (icce.top)

1.2实现方法:

①宝塔面板新建网站:mqtt.yh***.com ,申请免费证书,然后配置SSL。

②网站配置修改,在配置文件中添加以下内容:

注意:端口选择8083/8084 等,参考:配置说明 | EMQX 企业版 4.4 文档

bash 复制代码
 # 添加反向代理,重点!解决android无法连接mqtt问题
    location /mqtt {
      proxy_pass http://127.0.0.1:8083/mqtt;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      # client_max_body_size 35m;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";    
    }

2、小程序编写

引入mqtt.min.js文件,MQTT 下载引入和配置连接 | ESP32全栈应用开发文档 (icce.top)

javascript 复制代码
<template>
	<view>
		<view class="btn-box status" style="width: 100%;">
			<u-button size="medium" :type="status==0?'default':'success'" @click="send" :loading="!linked">
			{{status==0?'运行设备':'暂停设备'}}</u-button>
		</view>
	</view>
</template>

<script>
	import mqtt from "../js/mqtt.min";
	let client = null; // MQTT服务
	export default {
		data() {
			return {
				loading:false,
				status:0,//设备状态,0关闭,1运行
				options: {
				      protocolVersion: 4, //MQTT连接协议版本
				      clientId: 'miniTest',
				      clean: false,
				      password: 'Ch199410',
				      username: 'taskone',
				      reconnectPeriod: 1000, //1000毫秒,两次重新连接之间的间隔
				      connectTimeout: 3 * 1000, //1000毫秒,两次重新连接之间的间隔
				      resubscribe: true //如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
				},
				topic:"BlueLED",//发布主题
				linked:false,//是否连接
			}
		},
		onReady() {
			this.connectMqtt()
		},
		destroyed() {
			client?.end(true, error => {});
			client = null;
		},
		methods: {
			//连接mqtt服务器
			connectMqtt() {
			  let that = this;
			  client = mqtt.connect("wxs://mqtt.yh**.com/mqtt", this.options); // 连接方法
			  client.on("connect", error => {
			    console.log("连接成功");
			    // 可以在这里写一些连接成功的逻辑
				that.linked  = true
				that.bindSubscribe()
			  });
			  client.on("reconnect", error => {
			    console.log("正在重连:", error);
			    wx.showToast({ icon: "none", title: "正在重连", });
			  });
			  client.on("error", error => {
			    console.log("连接失败:", error);
			    wx.showToast({ icon: "none", title: "MQTT连接失败", });
			  });
			  client.on("message", (topic, message) => {
			    console.log(topic,message)
			  });
			},
			//订阅主题
			bindSubscribe(){
				// 订阅一个主题
				client.subscribe(this.topic, { qos: 0 }, function (err) {
				  if (!err) {
				    console.log("成功");
				    wx.showToast({ icon: "none", title: "添加成功" });
				    // 可以在这里写一些订阅主题成功的逻辑
				  }
				});
			},
			//发送消息
			pushMsg(msg){
				let that = this
				client.publish(this.topic, msg, { qos: 0 }, err => {
				  if (!err) {
					  that.status = that.status==0?1:0
				    console.log("topic:", "想要发送消息的Topic变量", "成功发出消息", msg);
				  }
				});
			},
			send(){
				this.pushMsg(this.status==0?'on':'off')
			}
		}
	}
</script>

<style lang="less" scoped>
.btn-box{
	width: 100%;
	text-align: center;
	padding:50rpx 0;
}
</style>

运行显示MQTT连接成功:

3、小程序连接MQTT问题

真机运行可能会遇到问题,小程序连接MQTT问题和方法

相关推荐
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
東雪蓮☆2 天前
深入理解 LVS-DR 模式与 Keepalived 高可用集群
linux·运维·服务器·lvs
2501_915918412 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
乌萨奇也要立志学C++2 天前
【Linux】进程概念(二):进程查看与 fork 初探
linux·运维·服务器
绿箭柠檬茶2 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
00后程序员张2 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
獭.獭.2 天前
Linux -- 信号【上】
linux·运维·服务器
路由侠内网穿透2 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
ZERO_pan2 天前
服务器装机遇到的问题
运维·服务器
l1t2 天前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb