A Permanent Two-Way Channel

A regular HTTP request is " ask → answer → connection closes. " WebSocket opens a permanent, bidirectional channel — data can flow in both directions instantly, at any time.

When to Use WebSockets

  • Live chat — messages arrive immediately without polling
  • Collaborative tools — Google Docs-style real-time editing
  • Live sports scores / stock prices — server pushes updates as they happen
  • Online multiplayer games — low-latency bidirectional data
const socket = new WebSocket('wss://api.example.com/ws');

// Connection opened
socket.addEventListener('open', () => {
  socket.send(JSON.stringify({ type: 'join', room: 'general' }));
});

// Receive messages from server
socket.addEventListener('message', (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
});

// Connection closed
socket.addEventListener('close', (event) => {
  console.log('Disconnected. Code:', event.code);
});

// Send a message anytime
function sendMessage(text) {
  socket.send(JSON.stringify({ type: 'message', text }));
}
Note

The key difference: with WebSocket, the server can push data to you at any time — without you requesting it first.