blog.dopana

Back

HTTP là request-response — client hỏi, server trả lời. WebSocket là kết nối 2 chiều, liên tục — cả hai đều có thể gửi bất kỳ lúc nào.

WebSocket vs HTTP#

HTTPWebSocket
Client gửi request → Server trả responseKết nối persistent, 2 chiều
Mở/kết nối mỗi requestHandshake 1 lần, giữ kết nối
Polling cho real-time (kém hiệu quả)Push real-time tự nhiên
Header lớn mỗi requestHeader nhỏ sau handshake

WebSocket Cơ Bản#

Server (Node.js + ws)#

Client#

Broadcast — Gửi Đến Tất Cả Client#

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    // Gửi cho tất cả client khác
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data.toString());
      }
    });
  });
});
typescript

Rooms — Phòng Chat#

Scale WebSocket — Nhiều Server#

Một server WebSocket không scale được — kết nối không share giữa các server.

Giải Pháp: Pub/Sub + Sticky Session#

Client A → Server 1 → Redis Pub/Sub → Server 2 → Client B
plaintext

Sticky session — đảm bảo client luôn kết nối cùng server (dùng IP hash cookie).

WebSocket với Bun#

Bun WebSocket built-in — không cần thư viện, pub/sub tích hợp sẵn.

WebSocket Với Cloudflare Durable Objects#

Durable Objects cho WebSocket real-time có state, scale global:

Auth WebSocket#

Xác thực khi handshake:

wss.on('connection', (ws, request) => {
  const token = new URL(request.url!, `http://${request.headers.host}`)
    .searchParams.get('token');

  if (!token || !verifyToken(token)) {
    ws.close(4001, 'Unauthorized');
    return;
  }

  const user = decodeToken(token);
  ws.userId = user.id;
});
typescript

Client:

const ws = new WebSocket('ws://localhost:8080?token=abc123');
typescript

Reconnection — Auto Retry#

Khi Nào Dùng WebSocket?#

  • Chat, messaging
  • Live notifications
  • Collaborative editing (Google Docs)
  • Real-time dashboard, trading
  • Multiplayer games
  • Live streaming updates

Không dùng WebSocket cho: CRUD API, request-response đơn giản — HTTP vẫn tốt hơn.

Kết Luận#

WebSocket là công cụ mạnh cho real-time. Bắt đầu đơn giản với ws (Node.js) hoặc built-in WebSocket của Bun. Scale với Redis Pub/Sub. Nhớ xử lý reconnection, auth, và heartbeat (ping/pong) để kết nối ổn định.

Tài liệu tham khảo#