M1LKYW4Y M1LKYW4Y - 2 months ago 12
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

childChannel.write(x);


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)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() { @Override
public void initChannel(SocketChannel ch) throws Exception {
//ch.pipeline().addLast(new TimeEncoder(),new DiscardServerHandler());
ch.pipeline().addLast(
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...*********


Thanks!

Answer

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

   @Override
   public void channelActive(ChannelHandlerContext ctx) {
       // closed on shutdown.
       allChannels.add(ctx.channel());
       super.channelActive(ctx);
   }
}

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