2014-12-13 357 views
3

我想向所有活動客戶端發送消息。websocket從服務器向所有客戶端發送消息

@OnMessage 
public void onMessage(String message, Session session) { 
    switch (message) { 
    case "latencyEqualize": 

     for (Session otherSession : session.getOpenSessions()) { 
      RemoteEndpoint.Basic other = otherSession.getBasicRemote(); 
      String data = "Max latency = " 
        + LatencyEqualizer.getMaxLatency(latencies);    
      try { 
       other.sendText(data); 
      } catch (IOException e) { 
       throw new RuntimeException(e); 
      } 
     } 
     break; 
    default: 

     RemoteEndpoint.Basic other = session.getBasicRemote();   
     try { 
      other.sendText(message); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

此代碼有問題。當我從第一個客戶端發送消息「latencyEqualize」時,服務器僅對同一個客戶端進行響應。其他客戶端不會收到消息「最大延遲= 15」。但是當第二個客戶端向服務器發送任何消息時,他會收到「Max latency = 15」。所有未來的服務器調用都會返回以前調用的消息。

有沒有辦法避免這種情況。我希望當其中一個客戶端向服務器發送「latencyEqualize」消息時,所有客戶端都會收到「Max latency」消息。

回答

4

只有一個客戶端收到您的消息的原因是session變量僅包含發送給您的消息的客戶端的連接。

如果將信息發送到所有客戶端,存儲它們的連接部分集合(例如,ArrayList<Session>)在onOpen()方法,然後遍歷儘管這集讓所有的客戶

+0

HTTP的連接:// WWW .byteslounge.com /教程/ java的EE-HTML5-的WebSockets與 - 多客戶端 - 例如 – KevinO 2016-01-14 19:01:23

相關問題