WebSocket is a communication protocol that provides full-duplex, bidirectional communication channels over a single TCP connection. Unlike HTTP, WebSocket allows both client and server to send messages at any time.
WebSocket
A protocol enabling full-duplex, real-time communication between client and server.
WebSocket vs HTTP
| Feature | WebSocket | HTTP |
|---|---|---|
| Connection | Persistent | Request-Response |
| Direction | Bidirectional | Client-initiated |
| Overhead | Low (after handshake) | Headers on every request |
| Real-time | Yes | Polling required |
Use Cases
- Chat Applications: Real-time messaging
- Live Dashboards: Stock prices, analytics
- Gaming: Multiplayer game state
- Notifications: Push updates to clients
- Collaborative Tools: Google Docs-style editing
Connection Lifecycle
- Handshake: HTTP upgrade request
- Open: Connection established
- Message: Data exchange
- Close: Connection terminated
Best Practices
- Implement reconnection logic
- Use heartbeat/ping-pong for connection health
- Handle connection errors gracefully
- Consider fallback to polling
Code Examples
Browser WebSocket
const ws = new WebSocket("wss://api.example.com/socket");
ws.onopen = () => {
console.log("Connected");
ws.send(JSON.stringify({ type: "subscribe", channel: "updates" }));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received:", data);
};
ws.onclose = () => console.log("Disconnected");Related Terms
Server-Sent Events (SSE)
A standard for pushing real-time updates from server to client over HTTP.
Read more
Mock Server
A fake server that simulates API responses for testing and development purposes.
Read more
API Testing
The process of verifying that APIs work correctly, securely, and perform well.
Read more
OpenAPI Specification
A standard format for describing REST APIs, enabling documentation and code generation.
Read more