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.
AI Transformation for Organisational Leaders
For directors, heads of function and founders: eight live evening sessions with Ehsan Gazar and Anoosh Zeighami, ending with a one-page 2027 AI plan for your organisation, built on a real workflow and ready for your leadership team.
$1,495, or $1,045 with code EARLYBIRD until 23 Oct.
View the live cohortKeep reading
- Your AI Pilot Saved Time. Why Didn't the Business Change?
- A Chatbot Answers. An Agent Does the Work. Here Is the Difference
- Why AI Can Crack a 90-Year-Old Maths Problem and Still Get Your Invoice Wrong
- I Use AI Every Day: Why I Built a Place to Practise the Old Problems
- How I Find Problems Worth Solving
- Notes on Software Quality