What Is WebSocket?
WebSocket is a protocol that establishes a persistent, full-duplex connection between client and server, allowing either side to send messages at any time wi...
Published October 9, 2026
WebSocket is a protocol that keeps a single TCP connection open between browser and server so both can send messages at any time, with low overhead. It powers chat, live dashboards and multiplayer games.
The concept
It starts as an HTTP request with an Upgrade header; after the handshake the connection switches to the WebSocket protocol (ws:// or wss://).
Unlike HTTP request/response, either side can push data without being asked.
Handshake then free messages
Practical examples
Browser client
const ws = new WebSocket('wss://example.com/live')
ws.onmessage = (e) => console.log(e.data)
ws.onopen = () => ws.send('hello')Node server (ws)
import { WebSocketServer } from 'ws'
new WebSocketServer({ port: 8080 }).on('connection', s => s.on('message', m => s.send('echo ' + m)))Reconnect logic
ws.onclose = () => setTimeout(connect, 1000)Common mistakes
- No reconnect or heartbeat handling.
- Using ws:// on HTTPS pages (mixed content).
- Not authenticating the connection.
Key takeaways
- Persistent two-way connection.
- Starts with HTTP upgrade.
- Handle reconnects and auth.
FAQ
WebSocket vs SSE?
SSE is one-way server-to-client over HTTP; WebSocket is two-way.
Do proxies support it?
Yes, if they forward the Upgrade headers.