ironie-nextjs/src/app/lib/websocket-client.ts
2025-05-28 00:41:23 +02:00

55 lines
1.4 KiB
TypeScript

export class WebSocketClient {
private ws: WebSocket | null = null
private baseUrl: string
private steamId: string
private listeners: ((data: any) => void)[] = []
constructor(baseUrl: string, steamId: string) {
this.baseUrl = baseUrl
this.steamId = steamId
}
connect() {
if (this.ws && this.ws.readyState === WebSocket.OPEN) return
const fullUrl = `${this.baseUrl}?steamId=${encodeURIComponent(this.steamId)}`
this.ws = new WebSocket(fullUrl)
this.ws.onopen = () => {
console.log('[WebSocket] Verbunden mit Server.')
}
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data)
//console.log('[WebSocket] Nachricht erhalten:', data)
this.listeners.forEach((listener) => listener(data))
}
this.ws.onclose = () => {
console.warn('[WebSocket] Verbindung verloren. Reconnect in 3 Sekunden...')
setTimeout(() => this.connect(), 3000)
}
this.ws.onerror = (error) => {
console.error('[WebSocket] Fehler:', error)
this.ws?.close()
}
}
onMessage(callback: (data: any) => void) {
this.listeners.push(callback)
}
send(message: any) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message))
} else {
console.warn('[WebSocket] Nachricht konnte nicht gesendet werden.')
}
}
close() {
this.ws?.close()
}
}