服务器发送事件不起作用 - 浏览器无法监听任何服务器发送事件的事件

时间:2013-11-28 08:52:37

标签: html5 jsp server-sent-events

我在我的项目中实现服务器发送事件(HTML5)而不使用node.js,它只是简单的网页(另一个JSP页面)调用,我得到它的响应。但是当我得到它的响应但没有方法/函数(onopen,onmessage或onerror)执行...

客户代码:

if (!!window.EventSource) {
            var source=new EventSource("kitAvailCall.jsp");
            source.onopen = function(){
                alert("Kit is not available");
                source.close();
            };
            source.onmessage=function(event){
                console.log(event.data);
                alert("Kit is not available");
            }
            source.onerror =function(){
                console.log("EventSOurce: Getting error call");
                alert("Kit is not available");
            }
        }

服务器端代码:

try{
    while(true) {
        Thread.sleep(15000);
        String IpAddress = (String) session.getAttribute("IPName");
        boolean bool;
        if(IpAddress != null && ((new Date()).getTime() - session.getLastAccessedTime())/1000 > 28){
            bool = sample.pingToKit((String) session.getAttribute("IPName"));
            System.out.println("Long polling request: "+bool);
            //if bool is false then i want to quit loop and back to browser
            if(bool == false){
                response.setHeader("Content-Type","text/event-stream");
            response.setHeader("Cache-Control", "no-cache");
                out.print("data: " + bool);
                out.flush();
                break;
            }
        }
    }
}catch(Exception e){
    System.out.println("Going bad CONN:"+ e);
}

1 个答案:

答案 0 :(得分:0)

我对Java知之甚少,但我猜想你可能正在监听你作为流发送的相同控制器/ jsp servlet(无论java中的路由数据)。 在kitavailcall.jsp以外的页面上收听。此脚本仅用于流式传输,使用除kitavailcall.jsp之外的其他视图/ html页面  您必须了解的是,SSE是一个并发进程,您创建另一个页面并使用该页面中包含的javascript(客户端代码)在该页面上运行。您的服务器也应该支持多线程。

相关问题