Java 绑定到不同端口/每个端口在Netty中有不同的处理程序的最佳方法是什么?,

Java 绑定到不同端口/每个端口在Netty中有不同的处理程序的最佳方法是什么?,,java,netty,Java,Netty,我想基于Netty构建一个应用程序,但需要同时绑定到不同的端口,并且每个端口都需要有不同的处理程序逻辑。如何在Netty中实现这一点 我在网上搜索过,知道我可以多次绑定(主机、端口),但这仍然意味着所有端口都将使用相同的处理程序管道 非常感谢您只需使用一个ChannelFactory创建几个ServerBootstrap实例。例如: NioServerSocketChannelFactory factory = new NioServerSocketChannelFactory(

我想基于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 {
             ...
        }
    });
}

我认为那不是真的。处理程序附加到通道,它们不是全局的。