我想构建一个基于Netty的应用程序,但需要同时绑定到不同的端口,并且每个端口需要有不同的处理程序逻辑。在Netty中如何做到这一点?
我在网上搜索了一下,我知道我可能可以多次绑定(主机,端口),但这仍然意味着所有端口将使用相同的处理程序管道。
非常感谢
您只需使用单个ChannelFactory
创建多个ServerBootstrap
实例。例如:
NioServerSocketChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
ServerBootstrap bootstrap1 = new ServerBootstrap(factory);
bootstrap1.setPipelineFactory(...);
bootstrap1.bind(new InetSocketAddress(port1));
ServerBootstrap bootstrap2 = new ServerBootstrap(factory);
bootstrap2.setPipelineFactory(...);
bootstrap2.bind(new InetSocketAddress(port2));
或者,您可以动态地修改管道。例如在channelBound
回调中:
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
ctx.getPipeline().addLast("new", new SimpleChannelUpstreamHandler() {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
...
}
});
}