I've implemented a endpoint to my spring-boot application that returns a server sent event to which I send a simple string to a few times. When a request is made to this endpoint it is opened and after that a error occurs. The strings I send don't seem to make it to the frontend.
Here is the controller:
@RequestMapping("/sseTest")
@Async
public ResponseBodyEmitter handleRequest() {
final SseEmitter emitter = new SseEmitter();
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> {
for (int i = 0; i < 500; i++) {
try {
emitter.send(123 , MediaType.TEXT_PLAIN);
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
emitter.completeWithError(e);
return;
}
}
emitter.complete();
});
return emitter;
}
And the frontend code that handles the requests:
const eventSource = new EventSource('http://localhost:8080/sseTest');
eventSource.onopen = e => console.log('open');
eventSource.onerror = e => {
if (e.readyState == EventSource.CLOSED) {
console.log('close');
} else {
console.log(e);
}
};
eventSource.onmessage = event => {
console.log(event.data);
};
The console logs the following:
open
Event {type: "error"}
The event is opened but then immediately a error is reported.