export type AutoReconnectOptions = boolean | {
maxRetries?: number
retryInterval?: number
onMaxRetriesReached?: Function
}
export enum ConnectionStatus {
Disconnected = 'DISCONNECTED',
Connected = 'CONNECTED',
Error = 'ERROR'
}
class SocketService {
private static instance: SocketService | null = null
private ws: WebSocket | null = null
private listeners: Record<string, Function[]> = {
}
private autoReconnect: AutoReconnectOptions = true
private retries: number = 0
private connectionStatus: ConnectionStatus = ConnectionStatus.Disconnected
private constructor() {
this.connect()
}
public static getInstance(): SocketService {
if (!SocketService.instance) {
SocketService.instance = new SocketService()
}
return SocketService.instance
}
public setAutoReconnectOptions(options: AutoReconnectOptions) {
this.autoReconnect = options
}
public connect() {
this.ws = new WebSocket('ws://localhost:3000/ws')<
WebSocket封装(TypeScript、单例模式、自动重连、事件监听、Vue中使用)
于 2024-04-24 11:12:01 首次发布