Sobes.tech
Middle

Tell me about SSE (Server-Sent Events) and compare it with WebSocket and polling.

sobes.tech AI

Answer from AI

Server-Sent Events (SSE) is a technology that allows a server to send a stream of updates to a client over a unidirectional HTTP connection. The client opens a connection to the server and listens for events that the server sends in real time.

Features of SSE:

  • Unidirectional: server → client.
  • Uses standard HTTP, easily passes through proxies and firewalls.
  • Automatically reconnects when the connection is lost.
  • Message format is simple, text-based (usually in the format "event: ...\ndata: ...\n\n").

Comparison with WebSocket:

  • WebSocket is a bidirectional protocol, allowing both client and server to exchange messages in real time.
  • WebSocket is more efficient for interactive applications with frequent data exchange in both directions.
  • SSE is simpler to implement for scenarios where the server just sends updates (e.g., news feeds, notifications).

Comparison with Polling:

  • Polling involves the client periodically making requests to the server to check for new data.
  • SSE is more efficient as the server sends data immediately, without delays and unnecessary requests.
  • Polling creates additional load on the server and network due to frequent requests.

Example of using SSE on the client:

const evtSource = new EventSource('/events');
evtSource.onmessage = function(event) {
  console.log('New message:', event.data);
};