What are WebSockets and how do they differ from HTTP?
Topic: microservices, Real-Time Communication. Level: Intermediate.
Answer
WebSocket is a protocol providing a **full-duplex, persistent** TCP connection between client and server. It starts as an HTTP request with an `Upgrade: websocket` header (the handshake), then switches protocols; afterward both sides can send messages any time with low overhead (small frames, no repeated headers). Unlike HTTP's request/response, either side can push. It supports text and binary. Ideal for chat, multiplayer games, collaborative editing, and live trading. Costs: stateful connections complicate load balancing/scaling and need heartbeats + reconnection logic.
```js
// After the HTTP Upgrade handshake, both sides push freely
const ws = new WebSocket('wss://example.com/chat')
ws.onopen = () => ws.send(JSON.stringify({ type: 'join', room: 'general' }))
ws.onmessage = e => appendMessage(JSON.parse(e.data)) // server can push anytime
// Client can also send anytime — full-duplex, unlike request/response HTTP
```