0

我想使用jsp实现服务器发送的事件,但它不起作用,我的代码如下所示,但它甚至不显示日期

日期.jsp

  <%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
  <%
    response.setContentType("text/event-stream;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Connection", "keep-alive");

  %>


  <%
    Date date = new Date();
    out.write(+date.toString()+);
    out.flush();
    try {
    Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    %>

我的 ex.html 代码是休闲的

<!DOCTYPE html>
<html>
<body>
     <h1>Getting server updates</h1>
     <div id="result"></div>

     <script>
     if(typeof(EventSource)!=="undefined")
     {
         var source=new EventSource("date.jsp");
         source.onmessage=function(event)
         {
             document.getElementById("result").innerHTML+=event.data + "<br>";
         };
     }
     else
     {
         document.getElementById("result").innerHTML="Sorry, your browser does not support   server-sent events...";
     }
    </script>

</body>
</html>

输出是:

获取服务器更新


也不显示日期...

我正在使用tomact服务器,代码有问题吗

4

1 回答 1

0

您应该使用可运行的东西,例如 body onLoad 或按钮 onClick 侦听器,您应该使用正确的 jsp 或 servlet 路径(不在 WEB-INF 文件夹中),您应该使用正确的事件数据格式,带有“data:”前缀和“\ n\n" 后缀。

ex.html

<!DOCTYPE html>
<html>
    <body onLoad = RegisterSSE()>
          <h1>Getting server updates</h1>
          <div id="result"></div>
          <script>
              function RegisterSSE()
              {
                  alert("wtf");
                  if(typeof(EventSource) != "undefined")
                  {
                      var source = new EventSource ("http://localhost:8080/web_war_exploded/date.jsp");
                      source.onmessage = function(event)
                      {
                          document.getElementById("result").innerHTML += event.data + "<br/>";
                      };
                  }
                  else
                  {
                      document.getElementById("result").innerHTML = "Sorry, your browser does not support   server-sent events...";
                  }
              }
          </script>
    </body>
    </html>

日期.jsp

<%
    response.setContentType("text/event-stream;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Connection", "keep-alive");

    Date date = new Date();
    out.write("event: server-time\n\n");
    out.write("data: "+date.toString() + "\n\n");
    out.flush();
    try {
        Thread.currentThread().sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
%>

毕竟你应该使用谷歌,你的问题并不新鲜,请看下面的链接:

java-servlet-and-server-sent-events

推送通知-for-java-web-app

如何推送通知-java-servlet-for-web-application

于 2014-02-01T18:35:02.190 回答