Spring Event Emitter stops sending events to previous clients on a new connection

纵然是瞬间 提交于 2019-12-12 02:18:40

问题


I'm new to Server-Sent-Events. I have an event emitter which sends updates in every 2 seconds(using SseEmitter, hosted on Tomcat) I see that the messages are not being sent to the previous windows when I open the URL in a new window. Please see the image below. Is it's an expected behavior of Server-Sent-Events? I nee to send updates to all the clients that are connected to my streaming URL. Do I need any additional configurations or settings on my application or the tomcat server? Please help

Here is the controller

@Controller
public class MySSEController {
    private final SseEmitter sseEmitter = new SseEmitter(100000l);
    private int counter = 0;

    @RequestMapping("/ssestream")
    public SseEmitter getRealTimeMessageAction() throws IOException {

        sseEmitter.send("MessageCounter : " + counter);
        return sseEmitter;
    }

    @Scheduled(fixedDelay = 2*1000)
    public void scheduledMsgEmitter() throws IOException
    {
        if(null != sseEmitter) {
            sseEmitter.send("MessageCounter : " + ++counter);
        }
    }
}

回答1:


Try this:

@Controller
public class MySSEController {
    private List<SseEmitter> sseEmitters = new ArrayList<>();

    private int counter = 0;

    @RequestMapping("/ssestream")
    public SseEmitter getRealTimeMessageAction() throws IOException {
        SseEmitter sseEmitter = new SseEmitter(100000l);
        sseEmitter.send("MessageCounter : " + counter);
        sseEmitters.add(sseEmitter);
        return sseEmitter;
    }

    @Scheduled(fixedDelay = 2 * 1000)
    public void scheduledMsgEmitter() {
        counter++;
        List<SseEmitter> toRemove = new ArrayList<>();

        for (SseEmitter sseEmitter : sseEmitters) {
            try {
                sseEmitter.send("MessageCounter : " + counter);
            } catch (IOException ignore) {
                toRemove.add(sseEmitter);
            }
        }

        for (SseEmitter remove : toRemove) {
            sseEmitters.remove(remove);
        }
    }
}


来源:https://stackoverflow.com/questions/42858697/spring-event-emitter-stops-sending-events-to-previous-clients-on-a-new-connectio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!