In real-time communication scenarios, WebSocket, HTTP polling, and long polling are three common technical solutions.
HTTP Polling
Working Principle
Client periodically sends HTTP requests to server asking if there is new data.
javascript// Client polling implementation setInterval(() => { fetch('/api/check-updates') .then(response => response.json()) .then(data => { if (data.hasUpdates) { console.log('Received updates:', data.updates); } }); }, 5000); // Request every 5 seconds
Advantages
- Simple implementation, good compatibility
- No special server configuration required
- Easy to understand and use
Disadvantages
- High latency: Up to one polling cycle wait
- Resource waste: Many invalid requests
- High server pressure: Frequent HTTP requests
- Bandwidth waste: HTTP headers in every request
HTTP Long Polling
Working Principle
After client sends request, server keeps connection open until new data arrives or timeout.
javascript// Client long polling implementation function longPoll() { fetch('/api/long-poll') .then(response => response.json()) .then(data => { console.log('Received data:', data); longPoll(); // Immediately start new request }) .catch(error => { setTimeout(longPoll, 5000); // Delay retry after error }); } longPoll();
Advantages
- Better real-time: Server returns immediately when data available
- Reduced requests: Fewer invalid requests compared to short polling
Disadvantages
- Complex connection management: Need to handle timeout and reconnection
- Server resource usage: Keep many open connections
- Still has latency: Timeout setting needs trade-off
WebSocket
Working Principle
Establish persistent connection, server and client can send messages at any time.
javascript// WebSocket implementation const ws = new WebSocket('ws://example.com/socket'); ws.onopen = () => { console.log('Connection established'); }; ws.onmessage = (event) => { console.log('Received message:', event.data); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ws.onclose = () => { console.log('Connection closed'); };
Advantages
- True real-time: Bidirectional communication, zero latency
- Low overhead: Only minimal data transmission after connection establishment
- Full-duplex: Server and client can send messages simultaneously
- Efficient: Reduce HTTP header overhead
Disadvantages
- Higher implementation complexity: Need to handle connection state, reconnection, etc.
- Higher server requirements: Need to support WebSocket protocol
- Compatibility issues: Old browsers don't support it
- Firewall restrictions: Some network environments may block WebSocket
Performance Comparison
| Metric | HTTP Polling | Long Polling | WebSocket |
|---|---|---|---|
| Real-time | Low | Medium | High |
| Server Load | High | Medium | Low |
| Bandwidth Usage | High | Medium | Low |
| Implementation Complexity | Low | Medium | High |
| Browser Compatibility | Best | Good | Good |
Use Cases
HTTP Polling
- Low data update frequency
- Low real-time requirements
- Simple configuration checks
Long Polling
- Need better real-time performance
- Sufficient server resources
- Don't want to introduce WebSocket complexity
WebSocket
- High real-time requirements
- Bidirectional communication needs
- Frequent data exchange
- Online chat, gaming, real-time monitoring, etc.