问题
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