サーブレットを使用して Java スタック上の Web アプリケーションに SSE を実装する作業を行っています。現在、2 つの重要な問題に直面しています。最初に Web ページとサーブレットの両方のコードを配置し、その後に直面している問題を配置します。
ウェブページコード:
<script type="text/javascript">
function registerSSE() {
var source = new EventSource("http://www.sample.com/BootStrap/NotificationServlet");
source.addEventListener('StartProductionRun', function(e) {
// Get the data and identify the instrument Name/Id
var dataReceived = e.data;
document.getElementById(dataReceived + "_button").disabled = true;
}, false);
}
function StartProduction(instrument) {
var dataString = 'instrumentName='+ instrument;
// call ajax to submit the form and start the production run
$.ajax({
type: 'POST',
url: 'http://localhost:8080/BootStrap/ProductionRunServlet',
data: dataString,
success: function() {
$('#Status').html("<div id='message'></div>");
$('#message').html("<h4 aling=\"centre\">Prudction Run for Instrument " + instrument + " initiated.</h4>")
.hide()
.fadeIn(5000);
}
});
}
</script>
サーブレット コード:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
NotificationService notificationService = null;
while (true) {
notificationService = NotificationService.getInstance();
if (notificationService.getNotificationCount() > 0 ) {
String notificationValue = notificationService.getNotification(0);
String[] keyValue = notificationValue.split(":");
out.print("event:" + keyValue[0] + "\n");
out.print("data: " + keyValue[1] + "\n");
out.print("retry:" + 1000 + "\n\n");
out.flush();
}
else {
out.print(": time stream \n");
out.print("retry:" + 1000 + "\n\n");
out.flush();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
今問題:
- Web ページは、同時に複数のユーザーによって表示されます。そして、そのページを閲覧しているすべてのユーザーにデータをプッシュしたいと考えています。現在、自分のマシンでローカルに実行している場合、Chrome と Firefox を開いても、両方のブラウザで通知を受け取りません。1つだけ入っています。
- また、ブラウザをしばらく実行したままにしておくと、サーブレットが特定のイベントに基づいてデータをプッシュしている場合でも、そのことがわかります。ブラウザに通知が届きません。
次のことを確認する必要があります。ページで何をしているかに関係なく、その特定のページを表示しているすべてのクライアントに通知がプッシュされるか、ページが情報の表示にのみ使用されます。
これを機能させるために私が得ることができるすべての助けを楽しみにしています。また、私が使用できる他の代替手段があるかどうかも知りたいです。