WebSocket isn't always the right tool. Here's an honest comparison to help you choose the right real-time technology for the job.
Full-duplex, persistent TCP connection. Both sides can send at any time.
// Client
const ws = new WebSocket('wss://api.example.com/ws');
ws.onmessage = (e) => console.log(e.data);
ws.send('Hello!'); // client can also send
Pros:
Cons:
ws://Use when: Chat, games, live collaboration, trading, multiplayer apps, anything bidirectional.
HTTP-based one-way push: server streams events to client over a persistent HTTP connection.
// Client — just one line!
const es = new EventSource('/stream');
es.onmessage = (e) => console.log(e.data);
// ONLY server → client
// Use fetch() for client → server