The Limitation of HTTP
Standard HTTP is a request-response protocol; the client asks for data, and the server responds. For real-time applications (like chats, live dashboards, or collaborative editors), HTTP polling is highly inefficient. WebSockets provide a persistent, bi-directional communication channel over a single TCP connection.
WebSocket Connection Lifecycle
- Handshake: The client sends an HTTP request requesting a protocol upgrade.
- Connection: The server accepts, and the connection remains open.
- Data Transfer: Both client and server send lightweight text or binary frames instantly without HTTP headers.
// Simple client-side WebSocket hookup
const socket = new WebSocket('wss://api.anntechnologies.in/ws');
socket.onopen = () => {
socket.send(JSON.stringify({ event: 'join', room: 'chat-1' }));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
updateChatUI(data);
};