优化ws心跳发送频率

dev
26947 2024-10-10 21:58:52 +08:00
parent 4fe98737b2
commit ae766a4559
1 changed files with 11 additions and 3 deletions

View File

@ -78,7 +78,8 @@ const chat = {
reconnect();
});
};
let heartbeatIntervalTime = 5000; // 初始心跳间隔时间(毫秒)
const maxHeartbeatInterval = 30000; // 最大心跳间隔时间毫秒例如设置为30秒
const startHeartBeat = () => {
heartBeatInterval = setInterval(() => {
if (socket && socket.readyState === 1) {
@ -90,7 +91,14 @@ const chat = {
socket.send({
data: JSON.stringify(info),
success: () => {
console.log("心跳包发送成功");
console.log("心跳包发送成功:",heartbeatIntervalTime);
// 如果当前心跳间隔小于最大值,则逐步增加心跳间隔
if (heartbeatIntervalTime < maxHeartbeatInterval) {
heartbeatIntervalTime += 1000; // 每次增加5秒
clearInterval(heartBeatInterval); // 清除旧的定时器
// 开始心跳
startHeartBeat();
}
},
fail: ()=>{
console.log("心跳包发送失败,尝试重新连接WebSocket");
@ -98,7 +106,7 @@ const chat = {
}
});
}
}, 5000); // 每5秒发送一次心跳包
}, heartbeatIntervalTime); // 每5秒发送一次心跳包
};
const stopHeartBeat = () => {