Websocket send message from 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);
        }
    }
}

      

There is something wrong with this code. When I send a "latencyEqualize" message from the first client, the server only responds to one client. Other clients do not receive the "Max. Timeout = 15" message. But when the second client sends any message to the server, it returns "Max. Timeout = 15" back. And all subsequent calls to the server return the message from the previous call.

Is there any way to avoid this. I want all clients to receive a "Max Latency" message when one of them has sent a "latencyEqualize" message to the server.

+3


source to share


1 answer


The reason only one client receives your message is because the variable session

only contains the connection of that client who sent you the message.



To send a message to all clients, store their connections in some collection (for example ArrayList<Session>

) in a method onOpen()

, and then iterate over that collection to get the connections of all your clients

+4


source







All Articles