logo

Achieve Ultimate Excellence

Server-Sent Events (SSE): Pushing Updates to Your Web Applications

Table of Contents

  1. Introduction to SSE

  2. Use Cases

  3. Architecture

  4. Message Format

  5. How SSE Works

  6. Implementing SSE

  7. Advantages and Limitations

  8. Comparison with WebSockets

  9. Conclusion

1. Introduction to SSE

Server-Sent Events are a part of the HTML5 specification that enables servers to send real-time updates to clients. Unlike traditional polling methods, SSE maintains an open connection, allowing the server to push updates as they occur.

2. Use Cases

SSE is commonly used in scenarios where real-time updates are essential, such as:

  • Stock Market Tickers: Displaying real-time stock prices.

  • News Feeds: Updating news articles as they are published.

  • Live Scoreboards: Showing live scores in sports events.

3. Architecture

When working with Server Sent Events, communications between client and server are initiated by the client (browser). The client creates a new JavaScript EventSource object, passing it the URL of an endpoint which is expected to return a stream of events over time.

The server receives a regular HTTP request from the client (these should pass through firewalls etc like any other HTTP request which can make this method work in situations where WebSockets may be blocked). The client expects a response with a series of event messages at arbitrary times. The server needs to leave the HTTP response open until it has no more events to send, decides that the connection has been open long enough and can be considered stale, or until the client explicitly closes the initial request.

4. Message Format

The Server Sent Events standard specifies how the messages should be formatted, but does not mandate a specific payload type for them.

A stream of such events is identified using the Content-Type "text/event-stream". Each event is formatted using a set of colon-separated key/value pairs with each pair terminated by a newline, and the event itself terminated by two newlines.

Here’s a template for a single event message:

id: <messageId - optional>
event: <eventType - optional>
data: <event data - plain text, JSON, ... - mandatory>

Here’s an example event that contains information about Qualcomm’s stock price:

id: 99
event: stockTicker
data: QCOM 64.31

In this case, the data is simple text, but it could equally be something more complex such as JSON or XML. The ID can also be any format that the server chooses to use.

5. How SSE Works

SSE operates over a standard HTTP connection. Here's how it works:

  • Client Request: The client opens a connection to the server by requesting a specific URL.

  • Server Response: The server accepts the connection and keeps it open.

  • Data Transmission: The server sends updates to the client as text-based messages.

  • Connection Maintenance: The connection remains open for continuous updates.

6. Implementing SSE

Server-Side

Using a language like Java with Spring Boot, you can create an SSE endpoint as follows:

@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getEvents() {
  return Flux.interval(Duration.ofSeconds(1))
             .map(sequence -> "Event " + sequence);
}

This code snippet defines a GET endpoint that produces a text event stream. It uses the Flux class from Project Reactor to create a stream of events, sending a new event every second.

Client-Side

On the client side, you can use JavaScript to connect to the SSE endpoint:

const eventSource = new EventSource('/events');
eventSource.onmessage = function(event) {
  console.log(event.data);
};

This JavaScript code creates a new EventSource object that connects to the server's "/events" endpoint. It then defines a callback function to handle incoming messages, logging them to the console.

7. Advantages and Limitations

Advantages:

  • Simple to implement.

  • Works over standard HTTP.

  • Efficient for one-way communication.

Limitations:

  • One-way communication only.

  • Limited browser support.

8. Comparison with WebSockets

While both SSE and WebSockets provide real-time communication, WebSockets offer full-duplex communication, whereas SSE is one-way. SSE is generally easier to implement but may not be suitable for all use cases.

9. Conclusion

Server-Sent Events offer a simple and efficient way to achieve real-time communication in web applications. By understanding the underlying principles and implementation details, developers can leverage SSE to enhance user experience with live updates.

avatar
Article By,
Create by
Browse Articles by Related Categories
Browse Articles by Related Tags
Share Article on:

Related posts