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

SSE
- 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
connect(){
console.log("connect");
let source = new EventSource("http://localhost:8080/hello");
source.addEventListener('spring',function(event:any){
console.log('------------'+event.data);
});
}


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;

@RestController
public class SSEHandler implements Runnable{

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

    @RequestMapping("/hello")
    public SseEmitter subscribe() {
        SseEmitter emitter = new SseEmitter();
        emitters.add(emitter);
        return emitter;
    }
    public void send(String data) throws IOException {
        for (SseEmitter emitter : emitters) {
            emitter.send(SseEmitter.event().name("spring").data(data));
        }
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(5000);
                send("Hello Client "+System.currentTimeMillis());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }   
    @PostConstruct
    public void start() {
        new Thread(this).start();
    }
}

No comments:

Post a Comment