u
This commit is contained in:
1 parent
db2208cc92
commit
35951777b0
13 files changed
+225
-151
No files matched your search
@@ -6,58 +6,153 @@ export function useWebSocket() {
|
||||
const isConnected = ref(false)
|
||||
const listeners = ref(new Set())
|
||||
|
||||
// 定时器
|
||||
let pingInterval, pongTimeout, connectTimeout
|
||||
let reconnectAttempts = 0
|
||||
let pingTimer = null
|
||||
let pongTimeout = null
|
||||
const PING_INTERVAL = 10000 // 收到PONG后间隔再发送下一次PING
|
||||
const PONG_TIMEOUT = 15000 // PING发送后15秒未收到PONG就重连
|
||||
|
||||
// 重连状态
|
||||
let reconnecting = false
|
||||
let reconnectNotification = null
|
||||
let reconnectDelay = 3000
|
||||
let currentUrl = null
|
||||
let isReconnecting = false
|
||||
|
||||
// 常量
|
||||
const MAX_RECONNECT_DELAY = 30000
|
||||
const PING_INTERVAL = 5000
|
||||
const PONG_TIMEOUT = 10000
|
||||
const CONNECT_TIMEOUT = 3000
|
||||
// --------------------
|
||||
// 私有方法
|
||||
// --------------------
|
||||
function cleanup() {
|
||||
if (pingTimer) {
|
||||
clearTimeout(pingTimer)
|
||||
pingTimer = null
|
||||
}
|
||||
if (pongTimeout) {
|
||||
clearTimeout(pongTimeout)
|
||||
pongTimeout = null
|
||||
}
|
||||
}
|
||||
|
||||
function handleDisconnect() {
|
||||
isConnected.value = false
|
||||
cleanup()
|
||||
}
|
||||
|
||||
function notifyListeners(message) {
|
||||
listeners.value.forEach(cb => cb(message))
|
||||
}
|
||||
|
||||
// --------------------
|
||||
// 心跳逻辑(链式)
|
||||
// --------------------
|
||||
function sendPing() {
|
||||
if (!socket.value || socket.value.readyState !== WebSocket.OPEN)
|
||||
return
|
||||
|
||||
try {
|
||||
sendMessage('PING')
|
||||
}
|
||||
catch (err) {
|
||||
console.error('发送 PING 失败', err)
|
||||
}
|
||||
|
||||
// 设置 PONG 超时
|
||||
if (pongTimeout)
|
||||
clearTimeout(pongTimeout)
|
||||
pongTimeout = setTimeout(() => {
|
||||
console.warn('未收到PONG,触发重连')
|
||||
handleReconnect()
|
||||
}, PONG_TIMEOUT)
|
||||
}
|
||||
|
||||
function handlePong() {
|
||||
// 收到 PONG,清理超时
|
||||
if (pongTimeout) {
|
||||
clearTimeout(pongTimeout)
|
||||
pongTimeout = null
|
||||
}
|
||||
|
||||
// 等 PING_INTERVAL 后再发送下一次 PING
|
||||
if (pingTimer)
|
||||
clearTimeout(pingTimer)
|
||||
pingTimer = setTimeout(sendPing, PING_INTERVAL)
|
||||
}
|
||||
|
||||
function startHeartbeat() {
|
||||
sendPing()
|
||||
}
|
||||
|
||||
// --------------------
|
||||
// 重连逻辑
|
||||
// --------------------
|
||||
function handleReconnect() {
|
||||
if (isReconnecting)
|
||||
return
|
||||
isReconnecting = true
|
||||
cleanup()
|
||||
isConnected.value = false
|
||||
socket.value?.close()
|
||||
|
||||
reconnectAttempts++
|
||||
if (reconnectNotification)
|
||||
reconnectNotification.close()
|
||||
reconnectNotification = ElNotification({
|
||||
title: '提示',
|
||||
message: `WebSocket 连接失败,正在第 ${reconnectAttempts} 次重连...`,
|
||||
type: 'warning',
|
||||
duration: 0,
|
||||
key: 'websocket-reconnect',
|
||||
})
|
||||
|
||||
const delay = Math.min(3000 * 2 ** (reconnectAttempts - 1), 30000)
|
||||
setTimeout(() => {
|
||||
isReconnecting = false
|
||||
connect(currentUrl)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function clearReconnectNotification() {
|
||||
if (reconnectNotification) {
|
||||
reconnectNotification.close()
|
||||
reconnectNotification = null
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------
|
||||
// 公共方法
|
||||
// --------------------
|
||||
function connect(url) {
|
||||
currentUrl = url
|
||||
if (isConnected.value)
|
||||
return
|
||||
if (socket.value)
|
||||
disconnect()
|
||||
|
||||
const ws = new WebSocket(url)
|
||||
socket.value = ws
|
||||
const newSocket = new WebSocket(url)
|
||||
|
||||
// 连接超时
|
||||
connectTimeout = setTimeout(() => !isConnected.value && ws.close(), CONNECT_TIMEOUT)
|
||||
|
||||
ws.onopen = () => {
|
||||
clearTimeout(connectTimeout)
|
||||
newSocket.onopen = () => {
|
||||
isConnected.value = true
|
||||
reconnecting = false
|
||||
reconnectDelay = 3000
|
||||
startHeartbeat()
|
||||
|
||||
// 关闭重连通知
|
||||
reconnectNotification?.close()
|
||||
reconnectNotification = null
|
||||
isReconnecting = false
|
||||
clearReconnectNotification()
|
||||
|
||||
ElNotification({
|
||||
title: '成功',
|
||||
message: 'WebSocket 已连接',
|
||||
title: '提示',
|
||||
message: 'WebSocket 连接成功',
|
||||
type: 'success',
|
||||
showClose: false,
|
||||
duration: 2000,
|
||||
})
|
||||
console.log('WebSocket 已连接')
|
||||
|
||||
reconnectAttempts = 0
|
||||
startHeartbeat()
|
||||
}
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
newSocket.onmessage = (event) => {
|
||||
let message
|
||||
try {
|
||||
const message = JSON.parse(event.data)
|
||||
if (message.type === 'PONG')
|
||||
return resetPongTimeout()
|
||||
message = JSON.parse(event.data)
|
||||
|
||||
if (message.type === 'PONG') {
|
||||
handlePong()
|
||||
return
|
||||
}
|
||||
|
||||
notifyListeners(message)
|
||||
}
|
||||
catch (err) {
|
||||
@@ -66,17 +161,17 @@ export function useWebSocket() {
|
||||
}
|
||||
}
|
||||
|
||||
ws.onclose = (event) => {
|
||||
newSocket.onclose = () => {
|
||||
handleDisconnect()
|
||||
if (event.code !== 1000)
|
||||
scheduleReconnect(url)
|
||||
if (!isReconnecting)
|
||||
handleReconnect()
|
||||
}
|
||||
|
||||
ws.onerror = (err) => {
|
||||
newSocket.onerror = (err) => {
|
||||
console.error('WebSocket错误:', err)
|
||||
handleDisconnect()
|
||||
scheduleReconnect(url)
|
||||
}
|
||||
|
||||
socket.value = newSocket
|
||||
}
|
||||
|
||||
function disconnect() {
|
||||
@@ -86,7 +181,8 @@ export function useWebSocket() {
|
||||
|
||||
function sendMessage(type, data) {
|
||||
if (isConnected.value && socket.value) {
|
||||
socket.value.send(JSON.stringify({ type, data }))
|
||||
const message = { type, data }
|
||||
socket.value.send(JSON.stringify(message))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,61 +191,6 @@ export function useWebSocket() {
|
||||
return () => listeners.value.delete(callback)
|
||||
}
|
||||
|
||||
function notifyListeners(message) {
|
||||
listeners.value.forEach(cb => cb(message))
|
||||
}
|
||||
|
||||
function startHeartbeat() {
|
||||
pingInterval = setInterval(() => {
|
||||
if (socket.value?.readyState === WebSocket.OPEN) {
|
||||
sendMessage('PING')
|
||||
pongTimeout = setTimeout(() => {
|
||||
console.warn('未收到PONG,关闭WebSocket')
|
||||
socket.value?.close()
|
||||
}, PONG_TIMEOUT)
|
||||
}
|
||||
}, PING_INTERVAL)
|
||||
}
|
||||
|
||||
function resetPongTimeout() {
|
||||
clearTimeout(pongTimeout)
|
||||
}
|
||||
|
||||
function handleDisconnect() {
|
||||
isConnected.value = false
|
||||
cleanup()
|
||||
}
|
||||
|
||||
function scheduleReconnect(url) {
|
||||
if (reconnecting)
|
||||
return
|
||||
reconnecting = true
|
||||
|
||||
// 显示一次重连提示
|
||||
if (!reconnectNotification) {
|
||||
reconnectNotification = ElNotification({
|
||||
title: '提示',
|
||||
message: 'WebSocket 连接断开,正在重连...',
|
||||
type: 'warning',
|
||||
showClose: false,
|
||||
duration: 0,
|
||||
})
|
||||
}
|
||||
|
||||
console.log(`WebSocket将在${reconnectDelay / 1000}s后尝试重连`)
|
||||
setTimeout(() => {
|
||||
connect(url)
|
||||
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY)
|
||||
reconnecting = false
|
||||
}, reconnectDelay)
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
clearInterval(pingInterval)
|
||||
clearTimeout(pongTimeout)
|
||||
clearTimeout(connectTimeout)
|
||||
}
|
||||
|
||||
onScopeDispose(() => disconnect())
|
||||
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user