gpt4 book ai didi

java - Java Web 服务器上的服务器发送事件

转载 作者:行者123 更新时间:2023-12-01 09:07:32 24 4
gpt4 key购买 nike

我有一个使用 Spring Framework 的 Java Web 服务器,我想使用服务器发送事件每秒向 Web 客户端发送通知。

我的这些通知 Controller 如下所示:

@Controller
public class NotificationController {

private static final String REST_PREFIX = "/rest/notifications";

@RequestMapping(value = {REST_PREFIX}, method = {RequestMethod.GET})
synchronized public void getMonitoringNotifications(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");

try {
PrintWriter out = response.getWriter();
int i = 0;

while (true) {
out.print("id: " + "ServerTime" + "\n");
out.print("data: " + (i++) + "\n\n");
out.flush();

Thread.currentThread().sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

我的问题是,客户端不是在 1 秒后接收每个通知,而是等待所有通知发送。如果我尝试在客户端上发送多个通知(假设为 30 个),我最终会收到所有通知。

我的客户端很简单,因为它只监听特定端点以获取通知:

<!DOCTYPE html>
<html>
<body>
<h1>Notification received : </h1>

<div id="ServerTime"></div>

<script>
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("https://10.241.53.185/rest/notifications");
source.addEventListener('message', function(event) {
console.log(event.data);
});
} else {
document.getElementById("ServerTime").innerHTML = "Working, processing, getting info....";
}
</script>

</body>
</html>

您能帮我解决这个问题吗?

谢谢

最佳答案

您需要使用SseEmitter来发送事件。请参阅Server-Sent Events with Spring (博客)。

您还应该从单独的线程发送事件(让请求线程返回)。

关于java - Java Web 服务器上的服务器发送事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41143099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com