Server Sent Events Close Connection - Spring Boot

Viewed 516

i have one question about SSEEmitter in Java Spring Boot. I have following code to etablish connection between client and server in Java Spring Boot. I have set the timeout of the SseEmitter - object to max value of long.

Now following scenary occurrs: I close the tab in the browser and the sseemitter object on the server don't close. So many objects are on the server. This leads to memory issues.

@RequestMapping(value = "/subscribe", consumes = MediaType.ALL_VALUE)
    public SseEmitter subscribe() {
        System.out.println("SUBSCRIBE CALLED!");
        System.out.println(emitters.size());
        SseEmitter x = new SseEmitter(Long.MAX_VALUE);
        try {
            x.send(SseEmitter.event().name("INIT"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        x.onCompletion(()->{
            System.out.println("ON COMPLETION CALLED!");
            emitters.remove(x);
        });
                
        x.onTimeout(()->{
            System.out.println("ON TIMEOUT CALLED!");
            emitters.remove(x);
        });
        emitters.add(x);
        return x;
    }

How can I say the client to close the object? Kind regards

1 Answers

I assume you are using "emitters" to send future updates. Try to complete the emitter and remove it from "emimtter" in the catch (IOException) block where you send the emitter update:

Related