在Netty中監聽多個端口是通過創建多個ServerBootstrap實例來實現的。每個ServerBootstrap實例都會使用不同的端口號和ChannelInitializer來處理不同的業務邏輯。
以下是一個簡單的示例代碼,演示如何在Netty中監聽多個端口:
public class MultiplePortServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap1 = new ServerBootstrap();
ServerBootstrap bootstrap2 = new ServerBootstrap();
bootstrap1.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new ChannelHandler1());
}
});
bootstrap2.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new ChannelHandler2());
}
});
ChannelFuture future1 = bootstrap1.bind(8080).sync();
ChannelFuture future2 = bootstrap2.bind(9090).sync();
future1.channel().closeFuture().sync();
future2.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
在這個示例中,我們創建了兩個ServerBootstrap實例,分別監聽8080和9090端口。每個ServerBootstrap實例使用不同的ChannelInitializer來處理不同的業務邏輯。
需要注意的是,在實際生產環境中,可能需要配置更多的參數和處理更多的異常情況。這里只是一個簡單的示例,用于演示如何在Netty中監聽多個端口。