let wsInstance = null;
let reconnectAttempts = 0; // 当前连接次数
const MAX_RECONNECT_ATTEMPTS = 99; // 最大连接次数
let messageListeners = []; // 消息监听器数组
const heartCheck = {
timeout: 1000, // 1秒发一次心跳
timeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj);
this.start();
},
start: function () {
this.timeoutObj = setTimeout(() => {
if (wsInstance && wsInstance.readyState === WebSocket.OPEN) {
// console.log('向服务发送消息,表示还在运行');
let msg = 'online:uuu';
let adminId = uni.getStorageSync("adminId");
if (adminId !== null && adminId !== '' && adminId !== undefined) {
msg = 'online' + ':' + adminId;
}
wsInstance.send({ data: msg }); // 发送心跳消息
this.reset(); // 重置心跳检测
}
}, this.timeout);
},
};
function connect() {
wsInstance = uni.connectSocket({
url: 'wss://xxx.xxxx.xxxx/ws', // 连接地址
success: () => {
console.log('WebSocket连接成功');
reconnectAttempts = 0;
heartCheck.start();
},
fail: (err) => {
console.error('WebSocket连接失败:', err);
},
});
wsInstance.onOpen(() => {
console.log('WebSocket连接成功');
reconnectAttempts = 0;
heartCheck.start();
});
wsInstance.onMessage((event) => {
console.log('接收到消息:', event.data);
// 分发事件到所有注册的监听器
messageListeners.forEach((listener) => {
listener(event.data);
});
});
wsInstance.onClose(() => {
console.log('WebSocket连接关闭,尝试重连');
heartCheck.reset();
if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
setTimeout(connect, 2000);
reconnectAttempts++;
}
});
wsInstance.onError((error) => {
console.error('WebSocket连接出错:', error);
});
}
function send(message) {
if (wsInstance) {
wsInstance.send({
data: message,
success: () => {
console.log('发送成功');
},
fail: (err) => {
console.error('发送失败:', err);
},
});
} else {
console.error('WebSocket未连接或连接已关闭');
}
}
function close() {
if (wsInstance) {
wsInstance.close({
success: () => {
console.log('WebSocket连接关闭成功');
},
fail: (err) => {
console.error('关闭连接失败:', err);
},
});
}
}
function addMessageListener(listener) {
messageListeners.push(listener);
}
function removeMessageListener(listener) {
messageListeners = messageListeners.filter((l) => l !== listener);
}
export default {
connect,
send,
close,
addMessageListener,
removeMessageListener,
};
2***@qq.com (作者)
我从if (wsInstance && wsInstance.readyState === WebSocket.OPEN) {这里开始移除的,但是真机上发现还是不行,onmessage没有触发,在网页上运行的不移除代码都能收到消息
2025-01-03 14:37
DCloud_UNI_FengXY
回复 2***@qq.com: 哪个平台的真机
2025-01-03 14:39
2***@qq.com (作者)
回复 DCloud_UNI_FengXY: HBuilderX4.44版本的真机,机器是OPPO reno9,但是我感觉安卓都有这种情况,我们的测试用的OPPO reno6pro也是一样的情况
2025-01-03 14:44