How to Use WebSockets for Real-Time Communication
Build real-time features with WebSocket connections. Chat, notifications, live updates, and collaborative editing.
How WebSockets Differ from HTTP
HTTP is requestβresponse: the client asks and the server answers, even though the underlying connection is often kept open and reused. A WebSocket (RFC 6455) starts as an HTTP request that asks to "upgrade"; after the server agrees, the same TCP connection carries small framed messages in both directions, whenever either side wants. That suits chat, presence, collaborative editing, live dashboards and multiplayer games. The alternative β polling with setInterval β sends full HTTP requests that mostly return nothing new, and adds up to one polling interval of delay.
Setting Up a Connection
Opening a connection: const ws = new WebSocket('wss://example.com/socket'). Always use wss:// (encrypted) in production. Events: ws.onopen (connected), ws.onmessage (incoming data in event.data), ws.onclose (disconnected), ws.onerror (error). Send with ws.send(JSON.stringify({ type: 'chat', text: 'Hello' })). Server side uses ws (Node.js), Django Channels (Python), or Gorilla (Go). Most communication uses JSON with a type field.
Worked Example: Bytes on the Wire
We pointed Chromium 141 at a raw TCP server on localhost and logged exactly what it sent: one fetch() poll, then a WebSocket handshake and one chat message (script and results in our test folder, October 13, 2026).
| What Chromium sent | Bytes |
|---|---|
| One HTTP poll request (headers only, no cookies) | 500 |
| WebSocket opening handshake (once per connection) | 472 |
One message, {"type":"chat","text":"Hi"} (27 bytes of JSON) | 33 β 2-byte header + 4-byte mask + payload |
| Close frame when the page closed the socket | 8 |
After the handshake, each small message costs about 6 bytes of framing instead of hundreds of bytes of headers β and real requests carry cookies, which often make them several kilobytes. Frames from client to server are always masked (the 4 extra bytes), as RFC 6455 requires; server frames are not.
Common Real-Time Patterns
Common patterns: Chat β clients send messages to server, which broadcasts to room. Presence β heartbeat pings track whoβs online. Live updates β server pushes data changes to subscribers. Collaborative editing β operational transforms or CRDTs synchronize state. Notifications β targeted messages to specific users. Define clear message schemas: { type: 'event', data: {...}, timestamp: '...' }.
Error Handling and Reconnection
Build reconnection from the start: retry with exponential backoff and jitter (for example 1 s, 2 s, 4 s β¦ capped at 30 s, each randomized) so thousands of clients do not reconnect at the same instant after an outage. Use the close event's code to decide whether to retry (1000 is a normal close; 1006 means the connection dropped without a close frame). The browser WebSocket API cannot send protocol-level ping frames, so detect dead connections with an application heartbeat β a small message every 20β30 s that the server answers. Queue outgoing messages while disconnected and resend after reconnecting, with IDs so the server can drop duplicates. Libraries such as Socket.IO add rooms, acknowledgements and fallbacks, but use their own protocol, so a Socket.IO client cannot talk to a plain WebSocket server.
Frequently Asked Questions
WebSocket vs Server-Sent Events?
How many connections can a server handle?
Do WebSockets work behind proxies?
Use the API Request Builder β free, no signup required.
β‘ Open API Request Builder