WebSockets Explained
Real-time communication between browser and server
What are WebSockets?
WebSocket is a communication protocol that creates a persistent, two-way connection between your browser and a server. Unlike regular web requests that open and close connections, WebSockets keep the connection open so data can flow back and forth instantly - like having a phone call instead of sending letters.
📅 Quick note: WebSockets have been around since 2011 and are supported by all modern browsers.
HTTP vs WebSockets
Traditional HTTP
sequenceDiagram
participant Browser
participant Server
Note over Browser,Server: First Request
Browser->>+Server: "Give me data"
Server-->>-Browser: "Here's your data"
Note over Browser,Server: Connection closes
Note over Browser,Server: Polling for updates
Browser->>+Server: "Any updates?"
Server-->>-Browser: "Nope, nothing new"
Note over Browser,Server: Connection closes
Note over Browser,Server: Still polling...
Browser->>+Server: "How about now?"
Server-->>-Browser: "Still nothing"
Note over Browser,Server: Connection closes
Problem: Each request requires a new connection. Like knocking on someone's door every time you want to say something!
WebSocket Connection
sequenceDiagram
participant Browser
participant Server
Note over Browser,Server: WebSocket Handshake
Browser->>Server: "Let's start a WebSocket"
Server->>Browser: "Connection established"
Note over Browser,Server: Real-time Communication
Server-->>Browser: "Update available!"
Browser-->>Server: "Got it, thanks!"
Browser-->>Server: "User clicked button"
Server-->>Browser: "Processing..."
Server-->>Browser: "Done! Here's result"
Note over Browser,Server: Connection stays open...
Solution: One connection handles all communication. Like having an open phone line where both sides can talk anytime!
WebSocket Connection Flow
sequenceDiagram
participant Browser
participant Server
Note over Browser,Server: Initial Handshake
Browser->>Server: HTTP Upgrade Request
Server->>Browser: 101 Switching Protocols
Note over Browser,Server: WebSocket Connection Established
Server-->>Browser: Real-time data
Browser-->>Server: User action
Server-->>Browser: Instant response
Browser-->>Server: Another message
Note over Browser,Server: Connection stays open...
Server-->>Browser: Push notification
Browser-->>Server: Heartbeat ping
Server-->>Browser: Heartbeat pong
Key Benefits
Instant Two-Way Communication
Data flows instantly in both directions. Both browser and server can send messages anytime - no delays, no polling, just immediate responses.
Efficient & Lightweight
After the initial handshake, each message is tiny compared to HTTP requests. No need to resend headers every time - much less bandwidth used.
Quick Start
Getting started with WebSockets is surprisingly simple:
const socket = new WebSocket('ws://localhost:8080');
// Listen for messages
socket.onmessage = (event) => {
console.log('Received:', event.data);
};
// Send a message
socket.send('Hello Server!');
💡 Pro tip: For production apps, consider using Socket.io - it's a popular library that makes WebSockets even easier and adds fallback support for older browsers.
Common Use Cases
- Chat & Messaging: Instant messages, notifications, live comments. WhatsApp Web, Slack, Discord, Twitch chat.
- Live Data & Dashboards: Stock prices, sports scores, analytics dashboards, multiplayer game updates.
- Collaborative Tools: Google Docs, Figma, Notion - see everyone's changes live as they type or edit.
When to Use WebSockets
Use WebSockets When
- You need real-time, instant updates
- Data flows both ways frequently
- Building chat, games, or live features
- Pushing notifications or alerts
- Creating collaborative tools
- Live data monitoring or dashboards
Stick with HTTP When
- Simple request-response patterns
- Infrequent data updates are fine
- Loading web pages or assets
- RESTful API calls
- File uploads or downloads
- Simple forms and user actions
💡 Simple Rule: If you find yourself polling for updates every few seconds, WebSockets might be a better choice!
⚠️ Common gotcha: Use wss://
(not ws://
) for HTTPS sites to avoid security issues.