WebSockets & Real-Time Communication
What are the best practices for implementing WebSocket event handling?
class WebSocketEventHandler {
constructor() {
this.handlers = new Map();
this.setupWebSocket();
}
setupWebSocket() {
this.ws.onmessage = (event) => {
try {
const { type, payload } = JSON.parse(event.data);
this.dispatch(type, payload);
} catch (error) {
this.handleError(error);
}
};
}
on(eventType, handler) {
if (!this.handlers.has(eventType)) {
this.handlers.set(eventType, new Set());
}
this.handlers.get(eventType).add(handler);
return () => this.off(eventType, handler);
}
dispatch(type, payload) {
const handlers = this.handlers.get(type);
if (handlers) {
handlers.forEach(handler => {
try {
handler(payload);
} catch (error) {
this.handleError(error);
}
});
}
}
}