2013-11-28 113 views
0

我在我的項目中實現了服務器發送事件(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); 
} 

回答

0

我不太瞭解java,但我可以猜想,您可能正在監聽您作爲流發送的相同控制器/ jsp servlet(無論java中的路由數據)。 在除kitavailcall.jsp以外的頁面上進行收聽。此腳本僅用於流式傳輸,使用除了kitavailcall.jsp之外的其他視圖/ html頁面 您必須瞭解的是,SSE是一個併發進程,您可以創建另一個頁面並使用javascript(客戶端代碼)在該頁面上運行,包含在該頁面中。而你的服務器也應該支持多線程。

+0

我的客戶端代碼位於index.jsp上。我正在聽kitavailcall.jsp。 – Rickyrock