Search code examples
javawebsocketundertow

How can I broadcast a message to all clients connected to an Undertow websocket server?


This is my current setup for an Undertow websocket server:

    Undertow server = Undertow.builder()
            .addHttpListener(8080, "localhost")
            .setHandler(path()
                    .addPrefixPath("/", websocket((exchange, channel) -> {
                        channel.getReceiveSetter().set(new AbstractReceiveListener() {
                            @Override
                            protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
                                final String messageData = message.getData();
                                for (WebSocketChannel session : channel.getPeerConnections()) {
                                    WebSockets.sendText(messageData, session, null);
                                }
                            }
                        });
                        channel.resumeReceives();
                    }))).build();

This is copied from one of their demo files. I believe onFullTextMessage here broadcasts any messages it receives to all clients.

I want to be able to trigger this behavior on demand. So instead of having to receive a message and using an event handler to send out more messages, I want to be able to arbitrarily do server.send() and send a message to all connected clients.

I've looked around and haven't found anything that seems capable of achieving this. I don't relish the idea of tracking all WebSocketChannels and sending to each client manually. Surely, there's a method somewhere that I've overlooked?

I'd appreciate some pointers if it's not something that's just not possible!


Solution

  • You can broadcast the message to all the clients on the channel by getting all the connections to this canal and sending the message :

    channel.getPeerConnections().forEach(connection -> {
        WebSockets.sendText(messageData, connection, null);
    });