2016-03-05 183 views
1

我已經在本地GlassFish 4.1服務器上部署了Java Web應用程序,該服務器實現了與Web客戶端互操作的WebSockets。我能夠通過套接字成功執行客戶端到服務器的通信,但由於某種原因,服務器到客戶端的通信不起作用。WebSocket Javascript客戶端未收到來自服務器的消息

將消息發送到客戶端的Java代碼:

try 
{ 
    String msg = ServerClientInteropManager.toResponseJSON(response); 
    parentSession.getBasicRemote().sendText(msg); 
    FLAIRLogger.get().info("Sent response to client. Message: " + msg); 
} 
catch (IOException ex) { 
    FLAIRLogger.get().error("Couldn't send message to session " + parentSession.getid() + ". Exception - " + ex.getMessage()); 
} 

的JavaScript代碼:

pipeline_internal_onMessage = function(event) 
{ 
    var msg = JSON.parse(event.data); 
    console.log("Received message from server. Data: " + event.data); 
}; 

function pipeline_init() 
{ 
    if (PIPELINE !== null || PIPELINE_CONNECTED === true) 
    { 
     console.log("Pipline already initialized"); 
     return false; 
    } 
    else 
    { 
     var pipelineURI = "ws://" + document.location.host + document.location.pathname + "webranker"; 
     console.log("Attempting to establish connection with WebSocket @ " + pipelineURI); 

     if ('WebSocket' in window) 
      PIPELINE = new WebSocket(pipelineURI); 
     else if ('MozWebSocket' in window) 
      PIPELINE = new MozWebSocket(pipelineURI); 
     else 
     { 
      console.log("FATAL: No WebSockets support"); 
      alert("This browser does not support WebSockets. Please upgrade to a newer version or switch to a browser that supports WebSockets."); 
      return false; 
     } 

     // the other event listeners get added here 
     PIPELINE.onMessage = pipeline_internal_onMessage; 
     PIPELINE_CONNECTED = true; 

     window.onbeforeunload = function() { 
      pipeline_deinit(); 
     }; 

     console.log("Pipeline initialized"); 
     return true; 
    } 
} 

在onMessage功能從來沒有發射,即使在服務器成功調用sendText()方法。使用AsyncRemote產生相同的結果。兩端的onError偵聽器也不會報告任何內容。這是我第一次使用套接字,所以我可能會錯過一些基本的東西。

回答

1

更換

PIPELINE.onMessage = pipeline_internal_onMessage 

PIPELINE.onmessage = pipeline_internal_onMessage 

請參考here更多。

+0

是的,這是訣竅。非常感謝! – shadeMe

相關問題