websockets vs http
title: WebSockets vs. HTTP: Real-Time Communication
description: Why HTTP is too slow for chat apps. The persistent connection revolution.
date: 2024-03-20
category: Web & Network
order: 13
readingTime: 6 min read
The web was built on a simple premise: The Client asks, the Server answers. This is HTTP. But what if the Server wants to speak first?
The Problem with HTTP (Polling)
Imagine a chat app. You want to know if you have a new message.
- Browser: "Any new messages?" -> Server: "No."
- (Wait 2 seconds)
- Browser: "Any new messages?" -> Server: "No."
- (Wait 2 seconds)
- Browser: "Any new messages?" -> Server: "Yes, here it is."
This is called Polling. It is inefficient. It wastes bandwidth and battery life on mobile phones because you are constantly asking "Are we there yet?"
The Solution: WebSockets
A WebSocket is a different protocol (ws:// instead of http://).
- Handshake: The browser sends an HTTP request saying "I want to upgrade to WebSocket."
- Connection: If the server agrees, the connection stays open. It never closes.
- Push: Now, the server can send data to the browser whenever it wants, without being asked.
Analogy:
- HTTP is a letter. You send it, you wait for a reply.
- WebSocket is a phone call. The line is open, and either person can speak at any time.
When to use which?
- Use HTTP for fetching documents, images, or REST APIs. (State is not maintained).
- Use WebSockets for Chat apps, Live Stock Tickers, Multiplayer Games, or Collaborative Editing (like Google Docs).