Script Valley
WebSockets & Real-Time Applications
Browser WebSocket APILesson 2.3

How to send and receive structured messages with WebSocket

JSON message envelope, type field pattern, onmessage parsing, binary vs text frames, message dispatch map, error handling on parse, send queue

Give Every Message a Type

WebSocket sends raw strings or binary. Without structure, your onmessage handler becomes an unreadable if-chain. Adopt a message envelope:

// Every message has { type, payload } function send(ws, type, payload) { ws.send(JSON.stringify({ type, payload })); } // Dispatch map const handlers = { chat: (payload) => renderMessage(payload), presence: (payload) => updatePresence(payload), error: (payload) => showError(payload.message), }; ws.onmessage = (event) => { let msg; try { msg = JSON.parse(event.data); } catch { console.error('Invalid JSON frame:', event.data); return; } const handler = handlers[msg.type]; if (handler) { handler(msg.payload); } else { console.warn('Unknown message type:', msg.type); } };

Sending Binary Data

Pass an ArrayBuffer, TypedArray, or Blob to send() to transmit binary frames. The receiver's event.data will be a Blob by default. Set ws.binaryType = 'arraybuffer' before connecting to receive ArrayBuffer directly — easier to parse with DataView. Use binary frames for audio, images, or performance-critical numeric streams where JSON overhead matters.

Up next

WebSocket heartbeat and keep-alive implementation

Sign in to track progress