M1LKYW4Y M1LKYW4Y - 11 months ago 50
Java Question

How do get a pointer to child channels from ServerBootStrap in Netty 4

I'm trying to figure out how best to get a pointer to the channels spawned by my server bootstrap. The idea being that I might later do something like


This is the code I currently have.

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.childHandler(new ChannelInitializer<SocketChannel>() { @Override
public void initChannel(SocketChannel ch) throws Exception {
//ch.pipeline().addLast(new TimeEncoder(),new DiscardServerHandler());
new ObjectEncoder(),
new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
new ObjectEchoServerHandler());

ChannelFuture f = b.bind(port).sync();
//f.channel() returns the NioServerSocketChannel ... not the child
//@TODO need child channel...*********


Answer Source

You might try to use ChannelGroup (see API doc), for instance:

To place before you create your ServerBootstrap

ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

You might decide to change the EventExecutor to workerGroup too.

Then in your ObjectEchoServerHandler, your constructor could set this ChannelGroup

public class ObjectEchoServerHandler extends xxx {
   ChannelGroup allChannels;
   public ObjectEchoServerHandler(ChannelGroup allChannels) {
      this.allChannels = allChannels;

   public void channelActive(ChannelHandlerContext ctx) {
       // closed on shutdown.

And then you can use the group to send message to who you want, all or a specific one.