Long Polling, SSE và WebSocket là 3 cách server push data đến client, khác nhau về directionality, overhead và độ phức tạp.
Long Polling: client gửi request, server giữ connection open cho đến khi có data mới (hoặc timeout), rồi response; client lập tức gửi request mới. Đơn giản, works everywhere, nhưng tốn nhiều connection hơn, overhead HTTP header mỗi request. Server-Sent Events (SSE): client gửi 1 GET request, server giữ connection và push events theo format data: ...\n\n. Unidirectional (server → client only), automatic reconnect, native browser support (EventSource API), over HTTP/1.1 có thể bị giới hạn 6 connections/domain nhưng HTTP/2 giải quyết. Phù hợp: notifications, live feeds, progress updates. WebSocket: bidirectional, full-duplex — cả client và server đều có thể initiate message. Overhead nhỏ hơn (binary frame). Phức tạp hơn (cần WebSocket server, proxy config). Phù hợp: chat, collaborative editing, game, trading.
Chọn SSE khi: chỉ server → client, HTTP/2 available, đơn giản hơn WS. Chọn WebSocket khi: cần bidirectional, low-latency message từ client → server thường xuyên.
Long Polling, SSE, and WebSocket are 3 ways for the server to push data to the client, differing in directionality, overhead, and complexity.
Long Polling: the client sends a request; the server holds the connection open until new data is available (or a timeout), then responds; the client immediately sends a new request. Simple, works everywhere, but uses more connections and incurs HTTP header overhead per request. Server-Sent Events (SSE): the client sends one GET request; the server holds the connection and pushes events in the format data: ...\n\n. Unidirectional (server → client only), with automatic reconnection and native browser support (EventSource API). Over HTTP/1.1 it may be limited to 6 connections per domain, but HTTP/2 removes this restriction. Best for: notifications, live feeds, progress updates. WebSocket: bidirectional and full-duplex — both client and server can initiate messages. Lower per-message overhead (binary frames). More complex to set up (requires a WebSocket-capable server and proxy configuration). Best for: chat, collaborative editing, games, and trading.
Choose SSE when: communication is only server → client, HTTP/2 is available, and simplicity is preferred over WebSocket. Choose WebSocket when: bidirectional communication is needed or the client frequently sends messages with low latency.