Traditional HTTP works extremely well for many applications.
But what happens when the server needs to send information to the browser immediately?
Consider:
- Chat applications
- Live dashboards
- Multiplayer games
- Trading interfaces
- Delivery tracking
Polling is one solution.
WebSockets provide another.
Traditional HTTP
A client might repeatedly ask:
Any new messages?
Then:
Any new messages?
Again:
Any new messages?
This creates unnecessary requests.
WebSockets
With WebSockets, the client establishes a persistent connection.
Browser ←────────→ Server
persistent
connection
Either side can send messages.
Node.js Example
Using a WebSocket library, a server can broadcast messages:
socket.on("message", (message) => {
broadcast(message);
});
The browser can listen:
socket.onmessage = (event) => {
console.log(event.data);
};
Why WebSockets Are Useful
They provide low-latency bidirectional communication.
For example, when someone sends a chat message:
User A
↓
Server
↓
User B
User B doesn't need to repeatedly ask whether a message arrived.
Things to Consider
Persistent connections create additional operational concerns:
- Connection management
- Authentication
- Reconnection
- Scaling
- Load balancing
- Message ordering
When running multiple servers, messages may need to be distributed between instances.
Final Thoughts
WebSockets are powerful when your application genuinely needs real-time communication.
For normal CRUD applications, standard HTTP APIs are often simpler and sufficient.
Top comments (0)