AndrewBourgeois
AndrewBourgeois

Reputation: 2765

Netty: send messages to all (TCP) clients from outside the pipeline

I'm migrating my "plain NIO" (= I used the packages from the JDK directly) TCP server to Netty 4.

I have threads that send messages to all clients, like health-checking packets, chat message broadcasts, direct chat messages to a single client, ... using a Collection of SocketChannels that I keep somewhere.

How do I do that in Netty? Would it be wise to simply share a ChannelGroup between one of the Netty handlers and the threads that need to send messages? The channel would look like this:

public class ChannelCollectorHandler extends ChannelInboundMessageHandlerAdapter<String> {

    private static final ChannelGroup channels = new DefaultChannelGroup();

    public SecureChatServerHandler(ChannelGroup channels) {
       this.channels = channels;
    }


    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
    }

    ...
}

in all the threads I would then simply do:

channels.write(...);

will that work?

Upvotes: 3

Views: 4500

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23557

Yes this will work without problems. ChannelGroup was designed for tasks like this.

Upvotes: 6

Related Questions