From 50fa3fe16e5419f4e6cc366d598decdc19ae98d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=99=8C?= Date: Thu, 21 Sep 2023 19:07:10 +0800 Subject: [PATCH] no message --- src/store/modules/socket.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/store/modules/socket.js b/src/store/modules/socket.js index 09bbc73..36f4ad7 100644 --- a/src/store/modules/socket.js +++ b/src/store/modules/socket.js @@ -1,19 +1,20 @@ import config from '@/config'; -import { - ref -} from 'vue'; +import { ref } from 'vue'; import tool from '@/utils/tool'; + let socket; let reconnectAttempts = 1; +let intervalId; // 用于保存心跳请求的定时器id const maxReconnectAttempts = 5; const heartbeatInterval = 50000; const socketState = ref(socket); + export function createWebSocket() { let socketurl = config.WEBSOCKET || null; if (socketurl) { try { socket = new WebSocket(socketurl); - socket.onopen = function() { + socket.onopen = function () { console.log('WebSocket连接成功'); var user = tool.data.get('user') || {}; var token = tool.cookie.get(config.SESSIONNAME); @@ -32,18 +33,21 @@ export function createWebSocket() { } reconnectAttempts = 0; // reset reconnect attempts + // 清除之前的定时器 + clearInterval(intervalId); + // 定时发送心跳请求 - setInterval(function() { + intervalId = setInterval(function () { socket.send(JSON.stringify({ type: 'ping' })); }, heartbeatInterval); } - socket.onerror = function() { + socket.onerror = function () { console.log('WebSocket连接发生错误'); reconnect(); } - socket.onclose = function() { + socket.onclose = function () { console.log('WebSocket连接关闭'); reconnect(); } @@ -58,7 +62,7 @@ export function createWebSocket() { function reconnect() { if (maxReconnectAttempts > reconnectAttempts) { - setTimeout(function() { + setTimeout(function () { createWebSocket(); console.log('WebSocket进行重连(' + reconnectAttempts); reconnectAttempts++; @@ -67,7 +71,9 @@ function reconnect() { console.log('WebSocket重连失败'); } } + createWebSocket(); + export default { state: socketState } \ No newline at end of file