Java 网络服务器上的服务器发送事件
Server-Sent Events on Java Web server
我有一个使用 Spring 框架的 Java Web 服务器,我想使用 Server Sent Events 每秒向 Web 客户端发送通知。
我的这些通知控制器如下所示:
@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(博客)。
您还应该从单独的线程发送事件(让请求线程 return)。
我有一个使用 Spring 框架的 Java Web 服务器,我想使用 Server Sent Events 每秒向 Web 客户端发送通知。
我的这些通知控制器如下所示:
@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(博客)。
您还应该从单独的线程发送事件(让请求线程 return)。