C
Network/Real-time/Lesson 08

Real-Time Communication — WebSocket · SSE · Long Polling

30 min·theory

Real-Time Communication — WebSocket · SSE · Long Polling

🎯 After reading this lesson

After finishing this lesson, you will be able to confidently do the following three things.

  • ✅ Differences between WebSocket vs SSE vs Long Polling
  • ✅ The fallback mechanism of socket.io
  • ✅ WebRTC P2P connections + STUN/TURN

Keep the learning objectives as a checklist, and close the lesson once you can answer all of them.

Comparing 4 Real-Time Communication Approaches

Real-time = server → client push (or bidirectional).

ApproachDirectionProtocolUse Case
PollingClient pullHTTPLightweight polling (e.g., every 5 seconds)
Long PollingPull (long wait)HTTPChat · notifications (wait until event)
SSEServer → ClientHTTPNotifications · live feeds (unidirectional)
WebSocketBidirectionalWS/WSSChat · games · real-time collaboration
gRPC streamingBidirectionalHTTP/2Internal MSA
WebRTCP2PUDPVideo · audio

Selection guide:

  • 🟢 Unidirectional notifications → SSE (simple · auto-reconnect)
  • 🟢 Bidirectional chat · games → WebSocket
  • 🟢 P2P video → WebRTC
  • 🟢 Polling + compatibility → Long Polling (legacy browsers)
  • 🔴 Simple polling → avoid if possible

WebSocket Behavior + Usage Patterns

WebSocket = bidirectional messages over a single TCP connection:Handshake (HTTP → WS upgrade):``GET /ws HTTP/1.1Upgrade: websocketConnection: UpgradeSec-WebSocket-Key: <base64>Sec-WebSocket-Version: 13Response:HTTP/1.1 101 Switching ProtocolsUpgrade: websocketSec-WebSocket-Accept: <hash>`Client (browser):`javascriptconst ws = new WebSocket('wss://example.com/ws');ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', room: 'general' }));ws.onmessage = (event) => { const msg = JSON.parse(event.data); console.log(msg);};ws.onerror = (e) => console.error(e);ws.onclose = () => console.log('Connection closed');`Server (Node.js + ws):`javascriptconst { WebSocketServer } = require('ws');const wss = new WebSocketServer({ port: 8080 });wss.on('connection', (ws) => { ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.type === 'chat') { // Broadcast wss.clients.forEach(c => { if (c.readyState === WebSocket.OPEN) { c.send(JSON.stringify({ user: msg.user, text: msg.text })); } }); } });});``Production libraries:- Socket.IO — fallback (XHR · Long polling), rooms · namespaces- Pusher · Ably · Supabase Realtime — managed services- Centrifugo · Mercure — self-hostedScaling patterns:- Redis Pub/Sub — message routing across multiple servers- Sticky session — same user always hits the same server (or share state via Redis)- Heartbeat (ping/pong) — detect broken connections (typically every 30 seconds)

SSE + Long Polling

SSE (Server-Sent Events) — unidirectional stream server → client:Client (browser):``javascriptconst es = new EventSource('/api/notifications');es.onmessage = (event) => { const data = JSON.parse(event.data); showNotification(data);};es.onerror = () => console.log('Reconnecting...'); // Automatic reconnectes.close(); // Close`Server (Node.js):`javascriptapp.get('/api/notifications', (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); const interval = setInterval(() => { res.write(data: ${JSON.stringify({ msg: 'hi', time: Date.now() })}

); }, 1000); req.on('close', () => clearInterval(interval));});`SSE advantages:- HTTP standard (firewall- and proxy-friendly)- Auto-reconnect- Simpler than WebSocket- Resume from the point of disconnection via the Last-Event-ID headerSSE disadvantages:- Unidirectional only (client → server requires a separate POST)- No IE support (negligible nowadays)- HTTP/1.1 concurrent connection limit (HTTP/2 or higher recommended)---Long Pollingdelay the response as long as possible:`1. Client: GET /poll?last=422. Server: holds the response until a new event arrives (up to 30 seconds)3. New event → respond immediately4. Or 30-second timeout → empty response5. Client: immediately polls again (back to 1)``Use cases:- Legacy browsers (IE9-)- Environments where WebSocket · SSE are blocked- Simple notifications (sub-second latency acceptable)In most cases → WebSocket · SSE are more efficient

🤖 Try asking AI like this

Once you understand the concepts in this lesson, you can give AI specific instructions. Instead of a vague 'fix this,' a vocabulary-driven request — that is the starting point for saving tokens.

  • 'Migrate this polling code to WebSocket (socket.io)'
  • 'Compare this SSE against WebSocket vs SSE and refactor it to whichever fits better'

Why this reduces tokens

Without understanding the concepts, after receiving an AI answer you still have to ask 'What does that mean?' again. That follow-up question is what eats tokens. Learn the concept once, and the conversation ends in one turn.

Real-time Communication — WebSocket·SSE·Long Polling - Network