修改积分计算
This commit is contained in:
244
http/websock.js
244
http/websock.js
@@ -1,50 +1,110 @@
|
||||
import { reactive, ref } from 'vue';
|
||||
|
||||
// WebSocket 工具类,封装了 WebSocket 的连接、发送、接收、心跳、重连和关闭等操作
|
||||
// WebSocket 工具类 - 优化版
|
||||
class WebsocketUtil {
|
||||
|
||||
// 构造函数,初始化 WebSocket 连接
|
||||
constructor(url, time, params) {
|
||||
this.url = url; // WebSocket 服务器的 URL
|
||||
this.params = params; // WebSocket 连接参数
|
||||
this.time = time; // 心跳发送的间隔时间(毫秒)
|
||||
this.socketTask = null; // WebSocket 任务对象
|
||||
this.isOpen = false; // WebSocket 连接是否打开
|
||||
this.url = url;
|
||||
this.params = params;
|
||||
this.time = time;
|
||||
this.socketTask = null;
|
||||
this.isOpen = false;
|
||||
this.isAppActive = true; // 应用是否活跃(前台)
|
||||
|
||||
// 定时器相关
|
||||
this.reconnectTimeout = null; // 重连定时器
|
||||
this.heartbeatInterval = null; // 心跳定时器
|
||||
this.heartbeatTimeout = null; // 心跳超时定时器(检测 pong 响应)
|
||||
this.checkConnectionInterval = null; // 连接状态主动检查定时器
|
||||
this.reconnectTimeout = null;
|
||||
this.heartbeatInterval = null;
|
||||
this.heartbeatTimeout = null;
|
||||
this.checkConnectionInterval = null;
|
||||
|
||||
// 消息回调数组
|
||||
this.messageCallbacks = []; // 存储外部注册的消息回调函数的数组
|
||||
this.messageCallbacks = [];
|
||||
|
||||
// 重连策略配置
|
||||
this.reconnectAttempts = 0; // 当前重连次数
|
||||
this.reconnectMaxAttempts = 5; // 最大重连次数(设为 Infinity 表示无限重试)
|
||||
this.reconnectDelay = 3000; // 基础重连延迟(毫秒)
|
||||
this.maxReconnectDelay = 30000; // 最大重连延迟(毫秒)
|
||||
this.reconnectAttempts = 0;
|
||||
this.reconnectMaxAttempts = 5;
|
||||
this.reconnectDelay = 3000;
|
||||
this.maxReconnectDelay = 30000;
|
||||
|
||||
// 初始化 WebSocket 连接
|
||||
// 事件监听器引用(用于销毁时移除)
|
||||
this.appShowListener = null;
|
||||
this.appHideListener = null;
|
||||
this.networkListener = null;
|
||||
this.visibilityChangeListener = null;
|
||||
|
||||
// 初始化事件监听
|
||||
this.initEventListeners();
|
||||
// 初始化 WebSocket 连接
|
||||
this.initializeWebSocket();
|
||||
}
|
||||
|
||||
// 监听设备唤醒事件(浏览器环境)
|
||||
// 初始化全局事件监听
|
||||
initEventListeners() {
|
||||
// 1. 监听应用显示/隐藏(Uniapp 全局事件)
|
||||
this.appShowListener = uni.onAppShow(() => {
|
||||
console.log('应用从后台回到前台');
|
||||
this.isAppActive = true;
|
||||
// 重置重连状态,立即尝试重连
|
||||
this.resetReconnectState();
|
||||
this.checkConnection();
|
||||
this.startHeartbeat();
|
||||
this.startConnectionCheck();
|
||||
});
|
||||
|
||||
this.appHideListener = uni.onAppHide(() => {
|
||||
console.log('应用进入后台');
|
||||
this.isAppActive = false;
|
||||
// 后台时暂停心跳和连接检查,避免无效重连
|
||||
this.pauseHeartbeat();
|
||||
this.pauseConnectionCheck();
|
||||
});
|
||||
|
||||
// 2. 监听网络状态变化
|
||||
this.networkListener = uni.onNetworkStatusChange((res) => {
|
||||
console.log('网络状态变化:', res);
|
||||
if (res.isConnected) {
|
||||
// 网络恢复,重置重连状态并立即重连
|
||||
this.resetReconnectState();
|
||||
this.checkConnection();
|
||||
}
|
||||
});
|
||||
|
||||
// 3. 监听页面可见性变化(Web 端兼容)
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
this.visibilityChangeListener = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
// 页面可见时,主动检查连接
|
||||
console.log('页面可见,激活连接');
|
||||
this.isAppActive = true;
|
||||
this.resetReconnectState();
|
||||
this.checkConnection();
|
||||
this.startHeartbeat();
|
||||
this.startConnectionCheck();
|
||||
} else {
|
||||
console.log('页面隐藏,暂停连接活动');
|
||||
this.isAppActive = false;
|
||||
this.pauseHeartbeat();
|
||||
this.pauseConnectionCheck();
|
||||
}
|
||||
});
|
||||
};
|
||||
document.addEventListener('visibilitychange', this.visibilityChangeListener);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化 WebSocket 连接
|
||||
// 重置重连状态(用于应用前台切换、网络恢复时)
|
||||
resetReconnectState() {
|
||||
this.reconnectAttempts = 0;
|
||||
this.reconnectDelay = 3000;
|
||||
if (this.reconnectTimeout) {
|
||||
clearTimeout(this.reconnectTimeout);
|
||||
this.reconnectTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化 WebSocket 连接
|
||||
initializeWebSocket() {
|
||||
console.log('初始化WebSocket连接');
|
||||
if (this.isOpen) {
|
||||
return;
|
||||
if (this.isOpen) return;
|
||||
|
||||
// 关闭之前可能存在的连接
|
||||
if (this.socketTask) {
|
||||
this.closeSocket();
|
||||
}
|
||||
|
||||
this.socketTask = uni.connectSocket({
|
||||
@@ -53,7 +113,7 @@ class WebsocketUtil {
|
||||
console.log('WebSocket连接请求发送成功');
|
||||
},
|
||||
fail: (error) => {
|
||||
console.error('WebSocket连接失败', error);
|
||||
console.error('WebSocket连接失败:', error);
|
||||
uni.$emit('is-socket-open', false);
|
||||
this.reconnect();
|
||||
}
|
||||
@@ -61,12 +121,9 @@ class WebsocketUtil {
|
||||
|
||||
// 连接打开事件
|
||||
this.socketTask.onOpen((res) => {
|
||||
console.log('WebSocket连接正常!==', res);
|
||||
console.log('WebSocket连接正常!', res);
|
||||
this.isOpen = true;
|
||||
// 重置重连状态
|
||||
this.reconnectAttempts = 0;
|
||||
this.reconnectDelay = 3000;
|
||||
// 启动心跳和消息监听
|
||||
this.resetReconnectState(); // 重置重连状态
|
||||
this.startHeartbeat();
|
||||
this.listenForMessages();
|
||||
uni.$emit('is-socket-open', true);
|
||||
@@ -74,33 +131,37 @@ class WebsocketUtil {
|
||||
|
||||
// 连接错误事件
|
||||
this.socketTask.onError((res) => {
|
||||
console.log('WebSocket连接错误!==', res);
|
||||
console.error('WebSocket连接错误:', res);
|
||||
uni.$emit('is-socket-open', false);
|
||||
this.reconnect();
|
||||
});
|
||||
|
||||
// 连接关闭事件
|
||||
this.socketTask.onClose((result) => {
|
||||
console.log('WebSocket连接已关闭', result);
|
||||
console.log('WebSocket连接已关闭:', result);
|
||||
this.isOpen = false;
|
||||
this.reconnect();
|
||||
// 只有应用活跃时才重连
|
||||
if (this.isAppActive) {
|
||||
this.reconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// 启动连接状态主动检查(30秒一次)
|
||||
// 启动连接状态主动检查
|
||||
this.startConnectionCheck();
|
||||
}
|
||||
|
||||
// 启动心跳检测
|
||||
// 启动心跳检测(仅在应用活跃时)
|
||||
startHeartbeat() {
|
||||
if (!this.isAppActive) return;
|
||||
|
||||
// 清除现有定时器
|
||||
if (this.heartbeatInterval) clearInterval(this.heartbeatInterval);
|
||||
if (this.heartbeatTimeout) clearTimeout(this.heartbeatTimeout);
|
||||
this.pauseHeartbeat();
|
||||
|
||||
this.heartbeatInterval = setInterval(() => {
|
||||
if (this.isOpen) {
|
||||
if (this.isOpen && this.isAppActive) {
|
||||
// 发送心跳包
|
||||
this.send(JSON.stringify({ "type": "ping_interval", "set": "pad" }));
|
||||
// 设置5秒超时:若未收到pong则重连
|
||||
// 5秒超时检测
|
||||
this.heartbeatTimeout = setTimeout(() => {
|
||||
console.log('心跳超时,主动断开并重连');
|
||||
this.closeSocket();
|
||||
@@ -110,28 +171,52 @@ class WebsocketUtil {
|
||||
}, this.time);
|
||||
}
|
||||
|
||||
// 暂停心跳检测
|
||||
pauseHeartbeat() {
|
||||
if (this.heartbeatInterval) {
|
||||
clearInterval(this.heartbeatInterval);
|
||||
this.heartbeatInterval = null;
|
||||
}
|
||||
if (this.heartbeatTimeout) {
|
||||
clearTimeout(this.heartbeatTimeout);
|
||||
this.heartbeatTimeout = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 启动连接状态主动检查(30秒一次)
|
||||
startConnectionCheck() {
|
||||
if (this.checkConnectionInterval) clearInterval(this.checkConnectionInterval);
|
||||
this.checkConnectionInterval = setInterval(() => {
|
||||
if (!this.isOpen && !this.reconnectTimeout) {
|
||||
console.log('主动检查到连接断开,触发重连');
|
||||
this.reconnect();
|
||||
}
|
||||
this.checkConnection();
|
||||
}, 30000);
|
||||
}
|
||||
|
||||
// 发送消息
|
||||
// 暂停连接状态检查
|
||||
pauseConnectionCheck() {
|
||||
if (this.checkConnectionInterval) {
|
||||
clearInterval(this.checkConnectionInterval);
|
||||
this.checkConnectionInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 主动检查连接状态
|
||||
checkConnection() {
|
||||
if (this.isAppActive && !this.isOpen && !this.reconnectTimeout) {
|
||||
console.log('主动检查到连接断开,触发重连');
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// 发送消息
|
||||
send(data, type) {
|
||||
if (this.socketTask && this.isOpen) {
|
||||
this.socketTask.send({
|
||||
data: data,
|
||||
success: (res) => {
|
||||
// 发送成功,重置心跳(可选,根据业务需求)
|
||||
this.startHeartbeat();
|
||||
success: () => {
|
||||
this.startHeartbeat(); // 发送成功重置心跳
|
||||
},
|
||||
fail: (error) => {
|
||||
console.error('消息发送失败', error);
|
||||
console.error('消息发送失败:', error);
|
||||
this.reconnect();
|
||||
}
|
||||
});
|
||||
@@ -140,13 +225,12 @@ class WebsocketUtil {
|
||||
}
|
||||
}
|
||||
|
||||
// 监听 WebSocket 消息
|
||||
// 监听 WebSocket 消息
|
||||
listenForMessages() {
|
||||
if (this.socketTask) {
|
||||
this.socketTask.onMessage((res) => {
|
||||
const data = res.data.toString();
|
||||
try {
|
||||
// 尝试解析JSON,处理pong响应
|
||||
const message = JSON.parse(data);
|
||||
if (message.type === 'pong') {
|
||||
// 收到pong,清除心跳超时
|
||||
@@ -155,25 +239,29 @@ class WebsocketUtil {
|
||||
} catch (e) {
|
||||
console.warn('消息解析失败(非JSON格式):', e);
|
||||
}
|
||||
// 触发外部注册的回调函数
|
||||
// 触发外部回调
|
||||
this.messageCallbacks.forEach(callback => callback(data));
|
||||
});
|
||||
} else {
|
||||
console.error('WebSocket 连接尚未建立,无法监听消息');
|
||||
}
|
||||
}
|
||||
|
||||
// 重连 WebSocket(指数退避策略)
|
||||
// 重连 WebSocket(指数退避 + 应用活跃检测)
|
||||
reconnect() {
|
||||
// 应用在后台时,延迟重连
|
||||
if (!this.isAppActive) {
|
||||
console.log('应用在后台,延迟重连');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
|
||||
|
||||
// 达到最大重连次数,停止重试(可根据需求调整为无限重试)
|
||||
// 达到最大重连次数,停止重试
|
||||
if (this.reconnectAttempts >= this.reconnectMaxAttempts) {
|
||||
console.log(`已达最大重连次数 ${this.reconnectMaxAttempts},停止重连`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 指数退避:延迟时间 = 基础延迟 * 2^重连次数,最大不超过maxReconnectDelay
|
||||
// 指数退避延迟
|
||||
const delay = Math.min(
|
||||
this.reconnectDelay * Math.pow(2, this.reconnectAttempts),
|
||||
this.maxReconnectDelay
|
||||
@@ -186,14 +274,7 @@ class WebsocketUtil {
|
||||
}, delay);
|
||||
}
|
||||
|
||||
// 主动检查连接状态
|
||||
checkConnection() {
|
||||
if (!this.isOpen && !this.reconnectTimeout) {
|
||||
this.reconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭 WebSocket 连接
|
||||
// 关闭 WebSocket 连接
|
||||
closeSocket() {
|
||||
if (this.socketTask) {
|
||||
uni.closeSocket({
|
||||
@@ -202,36 +283,39 @@ class WebsocketUtil {
|
||||
this.isOpen = false;
|
||||
},
|
||||
fail: (error) => {
|
||||
console.error('关闭WebSocket连接失败', error);
|
||||
console.error('关闭WebSocket连接失败:', error);
|
||||
}
|
||||
});
|
||||
this.socketTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 外部注册消息回调函数
|
||||
// 外部注册消息回调
|
||||
onMessage(callback) {
|
||||
this.messageCallbacks.push(callback);
|
||||
}
|
||||
|
||||
// 外部注销消息回调函数
|
||||
// 外部注销消息回调
|
||||
offMessage(callback) {
|
||||
// 若传入callback,则移除指定回调;否则清空所有回调
|
||||
if (callback) {
|
||||
this.messageCallbacks = this.messageCallbacks.filter(cb => cb !== callback);
|
||||
} else {
|
||||
this.messageCallbacks = [];
|
||||
}
|
||||
this.messageCallbacks = callback
|
||||
? this.messageCallbacks.filter(cb => cb !== callback)
|
||||
: [];
|
||||
}
|
||||
|
||||
// 销毁 WebSocket 连接,清理资源
|
||||
// 销毁 WebSocket 连接,清理资源
|
||||
destroy() {
|
||||
this.closeSocket();
|
||||
// 清除所有定时器
|
||||
clearInterval(this.heartbeatInterval);
|
||||
clearTimeout(this.heartbeatTimeout);
|
||||
this.pauseHeartbeat();
|
||||
this.pauseConnectionCheck();
|
||||
clearTimeout(this.reconnectTimeout);
|
||||
clearInterval(this.checkConnectionInterval);
|
||||
// 移除所有事件监听
|
||||
if (this.appShowListener) uni.offAppShow(this.appShowListener);
|
||||
if (this.appHideListener) uni.offAppHide(this.appHideListener);
|
||||
if (this.networkListener) uni.offNetworkStatusChange(this.networkListener);
|
||||
if (this.visibilityChangeListener && typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', this.visibilityChangeListener);
|
||||
}
|
||||
// 清空回调数组
|
||||
this.messageCallbacks = [];
|
||||
console.log('WebSocket资源已销毁');
|
||||
|
||||
Reference in New Issue
Block a user