简体   繁体   中英

websocket send message from the server to all clients

I want to send a message to all active clients.

@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);
        }
    }
}

Something is wrong with this code. When i send message "latencyEqualize" from the first client the server answers only to the same client. Other clients don't receive message "Max latency = 15". But when the second client sends to server any message, he recieves back "Max latency = 15". And all future calls to server return the message from previous call.

Is there a way to avoid this. I want all clients get "Max latency" message when one of them send "latencyEqualize" message to the server.

The reason why only one client receives your message is that session variable contains connection only of that client who sent you message.

To send your message to all clients, store their connections in some collection (for example, ArrayList<Session> ) in onOpen() method, and then iterate though that collection to get connections of all of your clients

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM