Web & Internet
WebSockets (Real-Time Connections)
O(1) to send a message once the connection is open — there's no new connection setup cost per message, unlike issuing a fresh HTTP request each time.
The idea, in plain English
Regular HTTP (HyperText Transfer Protocol) is like exchanging letters by mail. Every time you want to say something new, you seal a fresh envelope, a brand-new request, and wait for a reply before you can send the next one. A WebSocket is a connection that, once opened, stays open in both directions. It's like hanging up the letters and picking up the phone instead. You dial once, and after that, either side can just speak whenever it wants, without hanging up and redialing for every single sentence.
How it works
- 1The client sends a special HTTP request asking to 'upgrade' the connection into a WebSocket.
- 2The server agrees, and from that moment on, the same connection stays open for both sides to use.
- 3Either side, client or server, can send a message at any time. Nobody has to ask permission first or wait to be asked.
- 4Messages arrive in the order they were sent, and the connection stays open until either side deliberately closes it.
When you'd use it
This applies to chat apps, live notifications, multiplayer games, live sports scores, and collaborative editing — anywhere the server needs to push updates the instant something happens, rather than waiting to be asked.
Common beginner mistakes
- Don't assume WebSockets replace HTTP entirely. Most apps still use regular HTTP requests for most things, and only add a WebSocket connection for the specific parts that need instant, two-way updates.
- Don't forget the connection can close unexpectedly — a dropped network, a server restart. Real code has to detect a closed connection and reconnect, or messages sent afterward simply go nowhere.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
client: hello server
server: hello client
server: score update: 2-1
connection closed
client tried to send after close: are you there?Not sure this is the right topic? See the learning paths → or where this leads →