WebSocket Support for Real-Time Bidirectional Communication
Detect WebSocket support for persistent, full-duplex communication channels. Covers connection lifecycle, binary data, and reconnection strategies.
Network
Detailed Explanation
WebSocket Detection
WebSocket provides a persistent, full-duplex communication channel over a single TCP connection, enabling real-time data exchange between the browser and server.
Detection
const hasWebSocket = typeof WebSocket !== 'undefined';
Connection Lifecycle
const ws = new WebSocket('wss://echo.example.com');
ws.onopen = () => {
console.log('Connected');
ws.send('Hello');
};
ws.onmessage = (event) => {
console.log('Received:', event.data);
};
ws.onclose = (event) => {
console.log('Closed:', event.code, event.reason);
};
ws.onerror = (error) => {
console.error('Error:', error);
};
Binary Data
ws.binaryType = 'arraybuffer'; // or 'blob'
ws.send(new Uint8Array([1, 2, 3, 4]));
Reconnection Strategy
function createReconnectingWS(url) {
let ws;
let retries = 0;
const maxRetries = 10;
function connect() {
ws = new WebSocket(url);
ws.onopen = () => { retries = 0; };
ws.onclose = () => {
if (retries < maxRetries) {
const delay = Math.min(1000 * 2 ** retries, 30000);
setTimeout(connect, delay);
retries++;
}
};
}
connect();
return { send: (d) => ws?.send(d) };
}
WebSocket vs Alternatives
| Feature | WebSocket | SSE | HTTP/2 Push | Long Polling |
|---|---|---|---|---|
| Bidirectional | Yes | No (server-only) | No | Simulated |
| Binary data | Yes | No | Yes | Yes |
| Overhead | Low | Low | Low | High |
| Proxy-friendly | Sometimes | Yes | Yes | Yes |
Use Case
Powers real-time applications like chat systems, collaborative editing, live dashboards, stock tickers, multiplayer games, and notification systems. Preferred over HTTP polling for any scenario requiring low-latency bidirectional communication.