英文:
SSE different client receive messages
问题
@GetMapping("/stream-sse-mvc")
public SseEmitter streamSseMvc() {
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
sseMvcExecutor.execute(() -> {
try {
for (int i = 0; true; i++) {
SseEventBuilder event = SseEmitter.event()
.data("SSE MVC - " + LocalTime.now().toString())
.id(String.valueOf(i))
.name("sse event - mvc");
emitter.send(event);
Thread.sleep(1000);
}
} catch (Exception ex) {
emitter.completeWithError(ex);
}
});
return emitter;
}
英文:
Im writing a messenger with Spring MVC , and I want that user which online could receive message from server. Best solution that I found its SSE , founded this method , but how server must know which user should receive this message , if all of active(online) user subscribed to this method ?
@GetMapping("/stream-sse-mvc")
public SseEmitter streamSseMvc() {
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
sseMvcExecutor.execute(() -> {
try {
for (int i = 0; true; i++) {
SseEventBuilder event = SseEmitter.event()
.data("SSE MVC - " + LocalTime.now().toString())
.id(String.valueOf(i))
.name("sse event - mvc");
emitter.send(event);
Thread.sleep(1000);
}
} catch (Exception ex) {
emitter.completeWithError(ex);
}
});
return emitter;
}
答案1
得分: 0
SSE有点像是单行道。对于双向通信,我认为你可能需要像WebSocket这样的其他东西,但我想你可以按照以下步骤进行:
- 当客户端首次联系时,将其ID传递给服务器。
- 服务器会在发送循环中跟踪该ID以及向该客户端发送的所有消息。我认为这并不能保证客户端收到了消息,但或许这已经足够了。
- 如果出现异常(通常是因为连接关闭),则客户端可能没有收到消息。
另一个选项是:
我想你也可以让客户端记录所有接收到的消息,并在收到时逐条报告,或者稍后批量报告。然而,在那种情况下,我开始想知道是否存在现有的同步解决方案可以为你处理这个问题。
英文:
SSE are kindof a one-way street. For a 2-way communication I think you'd need something else like web sockets, but I suppose you could do the following:
- When the client makes first contact, pass its ID to the server.
- The server keep track of that id and all the messages it has sent to that client in its send loop. I don't think this guarantees that the client received the message, but maybe it's good enough.
- If you get an exception (usually because the connection is closed), the client probably didn't receive the message.
ANOTHER OPTION:
I suppose you could also have the client record all the messages it receives and report them either one by one upon receipt or later as a batch. However, I start to wonder at that point if there aren't existing syncing solutions that would handle this for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论