服务器向所有客户端发送WebSocket消息

3
我想要向所有活跃的客户发送一条消息。
@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”的消息。但是当第二个客户端向服务器发送任何消息时,它会收到“最大延迟=15”的回复。并且所有未来对服务器的调用都会返回上一次调用的消息。
是否有避免这种情况的方法。我希望当其中一个客户端向服务器发送“latencyEqualize”消息时,所有客户端都能获得“最大延迟”消息。
1个回答

10

只有一个客户端接收到您的消息的原因是session变量仅包含发送给您消息的客户端的连接。

要将消息发送给所有客户端,请在onOpen()方法中将他们的连接存储在某个集合(例如ArrayList<Session>)中,然后通过迭代该集合获取所有客户端的连接。


2
http://www.byteslounge.com/tutorials/java-ee-html5-websockets-with-multiple-clients-example - KevinO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接