What is server sent Events (SSE)

SSE (Server Sent Events) are the one directional communication from server to client, supported by most recent browsers. It uses plain HTTP protocol for communication.

SSE vs WebSockets

- One directional communication. Service to browser
- Light weight than websocket
- Transported over simple HTTP instead of a custom protocol
- Can be poly-filled with javascript to "backport" SSE to browsers that do not support it yet.
- Built in support for automatic re-connection and event-id
- Allows only 6 open connections
- No binary support

Web socket
- Two directional communication
- Allows unlimited open connections
- Native support in more browsers

Simple SSE commucation code beween Spring and JavaScript

We will connect the SSE with the end point /hello
let source = new EventSource("http://localhost:8080/hello");

Spring controller class which handles the SSE.
Responsible for creating the connection and sends the message to all the connected client in each interval.

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.annotation.PostConstruct;

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

public class SSEHandler implements Runnable{

    private List<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    public SseEmitter subscribe() {
        SseEmitter emitter = new SseEmitter();
        return emitter;
    public void send(String data) throws IOException {
        for (SseEmitter emitter : emitters) {
    public void run() {
        while (true) {
            try {
                send("Hello Client "+System.currentTimeMillis());
            } catch (Exception e) {
    public void start() {
        new Thread(this).start();

No comments:

Post a Comment