What is the WebSocket API?
HTTP is request-response. The client asks, the server answers. That works for most things. But when you need real-time, bidirectional communication -- cha...
13 Oct 2023

HTTP is request-response. The client asks, the server answers. That works for most things. But when you need real-time, bidirectional communication -- chat apps, live dashboards, collaborative editing -- you need WebSockets.
The WebSocket API opens a persistent TCP connection between client and server. Either side can push messages at any time. No polling. No long-polling hacks. Just a clean, full-duplex channel.
It uses ws:// (unsecured) or wss:// (secured) protocols and works in any modern browser.
Why WebSockets Beat AJAX for Real-Time
AJAX was a clever hack. It was never designed for real-time communication. Polling the server every few seconds wastes bandwidth and adds latency. Long-polling is better but still clunky.
WebSockets were built specifically for bidirectional message pushing. The connection stays open. Messages flow instantly in both directions. That is a fundamentally different model.
Basic Usage
// Create a socket instance
var socket = new WebSocket('ws://localhost:8080');
From there you handle onopen, onmessage, onclose, and onerror events. The API is minimal and intentional.
When to Use Them
Use WebSockets when you need low-latency, real-time updates: chat, notifications, live collaboration, multiplayer games, financial tickers.
Do not use them for everything. Standard REST APIs are simpler, more cacheable, and easier to debug for typical CRUD operations. WebSockets add connection management complexity that is only justified when you actually need real-time behavior.