我正在试图弄清楚如何最好地获取指向我的服务器引导程序生成的通道的指针。这个想法是我以后可能会做类似
的事情childChannel.write(x);
这是我目前的代码。
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...*********
谢谢!
答案 0 :(得分:2)
您可以尝试使用ChannelGroup
(请参阅API文档),例如:
在创建ServerBootstrap之前放置
ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
您可能决定将EventExecutor更改为workerGroup。
然后在您的ObjectEchoServerHandler中,您的构造函数可以设置此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);
}
}
然后,您可以使用该组向您想要的人,全部或特定的人发送消息。