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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.