Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server-sent-event received and immediately an error is caught causing SSE to close

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.

like image 882
cjerik Avatar asked Nov 07 '22 14:11

cjerik


1 Answers

I had a similar issue. I had created a custom filter due to which it would ask to add Async support.

Custom Filter -

@WebFilter(urlPatterns="/*")
@Component
public class SessionFilter implements Filter {

The error it popped up was -

java.lang.IllegalStateException: Async support must be enabled on a servlet and for all filters involved in async request processing. This is done in Java code using the Servlet API or by adding "true" to servlet and filter declarations in web.xml.

I removed the custom filter. and it worked like a charm.

like image 108
kads Avatar answered Nov 14 '22 23:11

kads