WebSocket 即時通訊實作
WebSocket 在 Client 與 Server 之間建立持久的全雙工連線,非常適合聊天室、即時通知、協作編輯等場景。
原生 WebSocket
const ws = new WebSocket('wss://api.example.com/ws');
ws.onopen = () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'subscribe', channel: 'news' }));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
ws.onclose = () => {
console.log('Disconnected');
};
自動重連機制
function createReconnectingWebSocket(url, options = {}) {
let ws;
let retryCount = 0;
const maxRetries = options.maxRetries || 10;
function connect() {
ws = new WebSocket(url);
ws.onclose = () => {
if (retryCount < maxRetries) {
const delay = Math.min(1000 * 2 ** retryCount, 30000);
setTimeout(connect, delay);
retryCount++;
}
};
ws.onopen = () => { retryCount = 0; };
}
connect();
return { send: (data) => ws?.send(data) };
}
心跳機制
setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
Socket.IO 快速上手
import { Server } from 'socket.io';
const io = new Server(server);
io.on('connection', (socket) => {
socket.join('room-1');
io.to('room-1').emit('message', 'New user joined');
});