正式检测代码提交
This commit is contained in:
@@ -18,6 +18,12 @@ export default class SocketService {
|
||||
sendRetryCount = 0;
|
||||
// 重新连接尝试的次数
|
||||
connectRetryCount = 0;
|
||||
|
||||
heartbeatTimer;
|
||||
heartbeatInterval = 6000; // 心跳间隔,单位毫秒
|
||||
lastActivityTime= 0; // 上次活动时间戳
|
||||
reconnectDelay= 5000; // 重新连接延迟,单位毫秒
|
||||
|
||||
// 定义连接服务器的方法
|
||||
connect(url) {
|
||||
|
||||
@@ -38,6 +44,8 @@ export default class SocketService {
|
||||
this.connected = true;
|
||||
// 重置重新连接的次数
|
||||
this.connectRetryCount = 0;
|
||||
this.updateLastActivityTime();
|
||||
this.startHeartbeat();
|
||||
};
|
||||
// 1.连接服务端失败
|
||||
// 2.当连接成功之后, 服务器关闭的情况
|
||||
@@ -45,13 +53,18 @@ export default class SocketService {
|
||||
console.log('连接服务端失败');
|
||||
this.connected = false;
|
||||
this.connectRetryCount++;
|
||||
this.clearHeartbeat();
|
||||
setTimeout(() => {
|
||||
// this.connect();
|
||||
}, 500 * this.connectRetryCount);
|
||||
|
||||
|
||||
};
|
||||
// 得到服务端发送过来的数据
|
||||
this.ws.onmessage = (event) => {
|
||||
let message: { [key: string]: any };
|
||||
|
||||
|
||||
try {
|
||||
console.log('Received message:',event.data)
|
||||
message = JSON.parse(event.data);
|
||||
@@ -63,12 +76,45 @@ export default class SocketService {
|
||||
if (message?.type && this.callBackMapping[message.type]) {
|
||||
this.callBackMapping[message.type](message);
|
||||
} else {
|
||||
console.log("抛弃====>")
|
||||
console.log(event.data)
|
||||
/* 丢弃或继续写你的逻辑 */
|
||||
console.log("抛弃====>")
|
||||
console.log(event.data)
|
||||
/* 丢弃或继续写你的逻辑 */
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
startHeartbeat() {
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if ((Date.now() - this.lastActivityTime) > this.heartbeatInterval) {
|
||||
// 如果超过心跳间隔没有活动,发送心跳消息
|
||||
this.sendHeartbeat();
|
||||
}
|
||||
}, this.heartbeatInterval/2); // 每半个心跳间隔检查一次
|
||||
}
|
||||
sendHeartbeat() {
|
||||
console.log("进入心跳消息发送。。。。。。。。。。。。。")
|
||||
this.ws.send('alive');
|
||||
this.updateLastActivityTime(); // 发送心跳后更新活动时间
|
||||
}
|
||||
|
||||
|
||||
updateLastActivityTime() {
|
||||
this.lastActivityTime = Date.now();
|
||||
}
|
||||
|
||||
clearHeartbeat() {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 回调函数的注册
|
||||
registerCallBack(socketType, callBack) {
|
||||
this.callBackMapping[socketType] = callBack;
|
||||
|
||||
Reference in New Issue
Block a user