27 lines
677 B
JavaScript
27 lines
677 B
JavaScript
let socket = null
|
|
const handlers = {}
|
|
|
|
export function wsOnEvent(type, fn) {
|
|
handlers[type] = fn
|
|
}
|
|
|
|
export function wsConnect() {
|
|
if (socket) return
|
|
const token = localStorage.getItem('token') || ''
|
|
socket = new WebSocket('ws://localhost:8080/ws')
|
|
socket.onopen = () => socket.send(JSON.stringify({ token }))
|
|
socket.onmessage = (e) => {
|
|
try {
|
|
const msg = JSON.parse(e.data)
|
|
handlers[msg.type]?.(msg.event)
|
|
} catch (err) { console.error('[ws] message error', err) }
|
|
}
|
|
socket.onclose = () => { socket = null }
|
|
socket.onerror = (err) => console.error('[ws] error', err)
|
|
}
|
|
|
|
export function wsDisconnect() {
|
|
socket?.close()
|
|
socket = null
|
|
}
|