私はSpring Frameworkを使用しているJava Webサーバーを持っていて、サーバー送信イベントを使用して毎秒Webクライアントに通知を送信したいと考えています。これらの通知のためのJava 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'か' StreamingResponseBody'を使用してください。 –
情報ありがとうございます。私は別のスレッドでプリンタに書き込む必要があるので、私のコードでこの問題を発見しました。 – Ancuta