|
|
@ -1,6 +1,6 @@ |
|
|
|
import { Subject } from "rxjs"; |
|
|
|
|
|
|
|
export type SocketState = 'open' | 'close' | 'error' |
|
|
|
export type SocketState = "open" | "close" | "error"; |
|
|
|
|
|
|
|
class WebSocketClient { |
|
|
|
private ws: WebSocket | null = null; |
|
|
@ -9,9 +9,14 @@ class WebSocketClient { |
|
|
|
private maxReconnectAttempts: number = 5; |
|
|
|
private reconnectInterval: number = 3000; |
|
|
|
|
|
|
|
readonly dataOb = new Subject() |
|
|
|
readonly stateOb = new Subject<SocketState>() |
|
|
|
|
|
|
|
private dataSub = new Subject(); |
|
|
|
get dataOb() { |
|
|
|
return this.dataSub.asObservable(); |
|
|
|
} |
|
|
|
private stateSub = new Subject<SocketState>(); |
|
|
|
get stateOb() { |
|
|
|
return this.stateSub.asObservable(); |
|
|
|
} |
|
|
|
constructor(url: string) { |
|
|
|
this.url = url; |
|
|
|
} |
|
|
@ -41,7 +46,7 @@ class WebSocketClient { |
|
|
|
this.ws.onopen = () => { |
|
|
|
console.log("WebSocket 连接已建立"); |
|
|
|
this.reconnectAttempts = -1; // 重置重连次数
|
|
|
|
this.stateOb.next('open') |
|
|
|
this.stateSub.next("open"); |
|
|
|
}; |
|
|
|
|
|
|
|
// 接收消息的处理
|
|
|
@ -49,20 +54,20 @@ class WebSocketClient { |
|
|
|
try { |
|
|
|
const data = JSON.parse(event.data); |
|
|
|
// console.log('🚀 ~ WebSocketClient ~ bindEvents ~ data:', data)
|
|
|
|
this.dataOb.next(data) |
|
|
|
this.dataSub.next(data); |
|
|
|
} catch (error) { |
|
|
|
console.error("消息解析错误:", error); |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
this.ws.onclose = () => { |
|
|
|
this.stateOb.next('close') |
|
|
|
this.stateSub.next("close"); |
|
|
|
console.log("WebSocket 连接已关闭"); |
|
|
|
this.reconnect(); |
|
|
|
}; |
|
|
|
|
|
|
|
this.ws.onerror = error => { |
|
|
|
this.stateOb.next('error') |
|
|
|
this.stateSub.next("error"); |
|
|
|
console.error("WebSocket 错误:", error); |
|
|
|
}; |
|
|
|
} |
|
|
@ -106,3 +111,7 @@ export const createWebSocket = (url: string): WebSocketClient => { |
|
|
|
return client; |
|
|
|
} |
|
|
|
}; |
|
|
|
|
|
|
|
export const sharedWsUrl = `ws://${import.meta.env.VITE_API_HOST}:${import.meta.env.VITE_API_PORT}${ |
|
|
|
import.meta.env.VITE_WS_PATH |
|
|
|
}`;
|