WebSocket Real-Time Communication: Building Live Applications

WebSocket enables full-duplex communication between client and server. Unlike HTTP, it maintains a persistent connection for real-time data exchange.

## Why WebSocket?

- Real-time data (chat, notifications)
- Lower overhead than HTTP polling
- Bidirectional communication
- Gaming and collaboration tools

## Client-Side

```javascript
const ws = new WebSocket('wss://example.com/ws');

ws.onopen = () => {
 console.log('Connected');
 ws.send(JSON.stringify({ type: 'hello' }));
};

ws.onmessage = (event) => {
 const data = JSON.parse(event.data);
 console.log('Received:', data);
};

ws.onclose = () => {
 console.log('Disconnected');
 // Auto-reconnect
 setTimeout(() => connect(), 3000);
};
```

## Server-Side (Node.js)

```javascript
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
 ws.on('message', (data) => {
   // Broadcast to all clients
   wss.clients.forEach(client => {
     if (client.readyState === WebSocket.OPEN) {
       client.send(data);
     }
   });
 });
});
```

## Heartbeat

```javascript
// Client-side heartbeat
setInterval(() => {
 if (ws.readyState === WebSocket.OPEN) {
   ws.send(JSON.stringify({ type: 'ping' }));
 }
}, 30000);
```

## Reconnection Strategy

```javascript
function connect() {
 const ws = new WebSocket(url);
 ws.onclose = () => {
   setTimeout(connect, Math.min(retries++ * 1000, 30000));
 };
}
```

## Conclusion

WebSocket is essential for real-time features. Use it for chat, live updates, and collaborative editing. Handle reconnection and heartbeats for production reliability.

评论
暂无评论