DEV Community

Sadiul Hakim
Sadiul Hakim

Posted on

Server Sent Event

What is Server-Sent Event (SSE)?

Server-Sent Events (SSE) is a unidirectional real-time communication technology where a server can push events/messages to the client over a single long-lived HTTP connection.

  • Based on HTTP/1.1 (or HTTP/2).
  • Uses the text/event-stream content type.
  • Works natively in browsers with EventSource API.
  • Unlike WebSockets, SSE is server → client only (no client → server messages except normal HTTP requests).

How does SSE work?

  1. Client opens connection The browser (or client) makes a request to a server endpoint:
   const evtSource = new EventSource("/sse/stream");
Enter fullscreen mode Exit fullscreen mode
  1. Server responds with text/event-stream The server keeps the connection open and pushes events in this format:
   data: Hello World
   data: Another line

Enter fullscreen mode Exit fullscreen mode
  • data: – the actual message
  • blank line = end of event
  • supports id:, event: for reconnection & custom event types
  1. Client listens
   evtSource.onmessage = function(event) {
       console.log("Message:", event.data);
   };
Enter fullscreen mode Exit fullscreen mode
  1. Reconnection is automatic If connection drops, EventSource automatically retries (default 3s).

When to use SSE?

Best use cases:

  • Real-time notifications (chat updates, stock prices, social feeds).
  • Streaming updates (logs, monitoring dashboards).
  • Live scoreboards or live comments.
  • Situations where server → client only communication is needed.
  • Works well with HTTP/2 multiplexing.

When not to use SSE?

Avoid SSE if:

  • You need bi-directional communication → use WebSockets.
  • You expect huge number of connections (WebSockets/HTTP/2 may scale better).
  • You need binary data transfer (SSE is text only).
  • Client environment doesn’t support EventSource (e.g., some IoT devices, old browsers).

Example: SSE in Spring Boot

1. Controller with SseEmitter

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/sse")
public class SseController {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    @GetMapping("/stream")
    public SseEmitter stream() {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        executor.execute(() -> {
            try {
                for (int i = 1; i <= 10; i++) {
                    emitter.send(SseEmitter.event()
                            .id(String.valueOf(i))
                            .name("message")
                            .data("Message " + i));
                    Thread.sleep(1000); // simulate delay
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Frontend (HTML + JS)

<!DOCTYPE html>
<html>
<body>
    <h1>SSE Example</h1>
    <ul id="messages"></ul>

    <script>
        const evtSource = new EventSource("/sse/stream");

        evtSource.onmessage = (event) => {
            const li = document.createElement("li");
            li.textContent = event.data;
            document.getElementById("messages").appendChild(li);
        };
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • Open /sse/stream in browser → you’ll see server-pushed events.

Summary:

  • SSE = server → client stream over HTTP.
  • Use it for one-way, event-driven updates (lightweight vs WebSockets).
  • Spring Boot provides SseEmitter for easy implementation.

Top comments (0)