断线状态

This commit is contained in:
吉浩茹
2025-11-05 10:07:59 +08:00
parent f6cb5d4c26
commit c8f7242f7c
2 changed files with 139 additions and 18 deletions

View File

@ -29,6 +29,9 @@ function messageid2() {
}
var client;
// 重连计数器,记录连续失败的重连次数
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5; // 最大重连次数
// 创建MQTT连接
const createMqtt = () => {
@ -50,6 +53,18 @@ const createMqtt = () => {
}
try {
// 检查是否已经超过最大重连次数
if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
console.log(`❌ 已重连${MAX_RECONNECT_ATTEMPTS}次失败,停止继续连接`);
uni.hideLoading();
uni.showToast({
title: `连接失败,已重试${MAX_RECONNECT_ATTEMPTS}`,
icon: 'error',
duration: 3000
});
return;
}
if (!client) {
console.log('🔧 开始创建MQTT连接...');
console.log('🔧 MQTT URL:', mqtturl);
@ -68,6 +83,7 @@ const createMqtt = () => {
'MP-ALIPAY'
// #endif
)
console.log(`🔄 当前重连次数: ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS}`);
// 显示连接loading
uni.showLoading({
@ -85,6 +101,23 @@ const createMqtt = () => {
console.error('❌ 错误详情:', e.message);
console.error('❌ 错误堆栈:', e.stack);
// 连接失败时增加重连计数器
reconnectAttempts++;
console.log(`❌ 连接失败,当前重连次数: ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS}`);
// 检查是否超过最大重连次数
if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
console.log(`❌ 已达到最大重连次数${MAX_RECONNECT_ATTEMPTS}次,停止连接`);
uni.hideLoading();
uni.showToast({
title: `连接失败,已重试${MAX_RECONNECT_ATTEMPTS}`,
icon: 'error',
duration: 3000
});
client = null;
return;
}
// 连接失败时隐藏loading
uni.hideLoading();
// uni.showToast({
@ -104,6 +137,9 @@ const initEventHandleMqtt = (topicUrl) => {
client.on("connect", function() {
uni.hideLoading();
console.log("✅ MQTT连接成功");
// 连接成功,重置重连计数器
reconnectAttempts = 0;
console.log("✅ 重置重连计数器");
// 显示连接成功提示
// uni.showToast({
@ -160,9 +196,28 @@ const initEventHandleMqtt = (topicUrl) => {
// 当断开连接后,经过重连间隔时间重新自动连接到 Broker 时触发
client.on('reconnect', function() {
console.log('🔄 MQTT重新连接中...');
reconnectAttempts++;
console.log(`🔄 MQTT重新连接中... (第${reconnectAttempts}次重连)`);
// 检查是否超过最大重连次数
if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
console.log(`❌ 已达到最大重连次数${MAX_RECONNECT_ATTEMPTS}次,停止重连`);
uni.hideLoading();
uni.showToast({
title: `连接失败,已重试${MAX_RECONNECT_ATTEMPTS}`,
icon: 'error',
duration: 3000
});
// 停止重连,关闭客户端
if (client) {
client.end();
client = null;
}
return;
}
uni.showLoading({
title: "重新连接中..."
title: `重新连接中... (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`
});
});
@ -204,6 +259,9 @@ const closeMqtt = () => {
client.end();
client = null;
}
// 断开连接时重置重连计数器
reconnectAttempts = 0;
console.log('🔌 重置重连计数器');
};
// 使用pingResp心跳判断客户端和服务端是否还在连接着
@ -238,6 +296,9 @@ const getConnectionStatus = () => {
// 手动重连函数
const manualReconnect = () => {
console.log('🔄 手动触发重连');
// 手动重连时重置计数器,给用户重新开始的机会
reconnectAttempts = 0;
console.log('🔄 重置重连计数器,开始新的连接尝试');
closeMqtt();
setTimeout(() => {
createMqtt();