java - HTML5 服务器端事件 (SSE)

标签 java html servlets server-sent-events

我正在致力于使用 Servlet 在 Java Stack 上的 Web 应用程序中实现 SSE。我目前面临两个关键问题。让我首先放置网页和 Servlet 的代码,然后放置我面临的问题。

网页代码:

<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>

Servlet 代码:

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();
            }
    }
}

现在的问题是:

  1. 该网页将被多个用户同时查看。我希望将数据推送给所有查看该页面的用户。目前,当我在计算机上本地运行时,即使我打开 Chrome 和 Firefox,我也不会在这两个浏览器中收到通知。它只有一件。
  2. 此外,如果我让浏览器运行一段时间,我会发现即使 servlet 会根据某些事件推送数据。我在浏览器上没有收到通知。

我需要确保: 通知会推送给所有正在查看该特定页面的客户端,无论他们在该页面上执行什么操作,或者该页面仅用于查看信息。

期待我能得到的所有帮助来完成这项工作。另外,我有兴趣知道是否还有其他我可以使用的替代方案。

最佳答案

你的servlet代码工作得很好,尽管我没有在它上面做太多工作(曾经做过一个jsp项目)。我认为,你错过了 javascript 中的一些东西? 我认为javascript中也应该有一个计时器/线程/循环,以连续获取所有推送的数据。即,

setInterval(
function(){
// code which needs to run every 5sec
},5000);

希望这会对您有所帮助。

关于java - HTML5 服务器端事件 (SSE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18915974/

相关文章:

java - 我该怎么办 session URL 很长,我无法附加 JSESSIONID=389729387392。解决方案是什么?

javascript - 使用javascript调用Servlet post方法

java - 将 HttpServletRequest 对象作为参数传递

java - 如何从选定的集合中查找最近的城市

java - 返回方法无法解析为变量

html - 如何在 HTML 列表中使用字母 "Q"和 "A"

html - CSS - 使无衬线字体模仿等宽字体

java - JFreechart 编译时错误的演示示例?

java - 在 Java 中将图像转换为 2 色

javascript - 浏览器缩小会破坏页面布局