netty 多端口
时间: 2023-07-26 13:06:05 浏览: 21
Netty可以支持多端口监听,可以通过创建多个ServerBootstrap实例,每个实例监听一个端口。以下是一个简单的示例代码:
```java
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap1 = new ServerBootstrap();
bootstrap1.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port1))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new MyServerHandler());
}
});
ServerBootstrap bootstrap2 = new ServerBootstrap();
bootstrap2.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(port2))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new MyServerHandler());
}
});
ChannelFuture future1 = bootstrap1.bind().sync();
System.out.println("Server started and listening on " + future1.channel().localAddress());
ChannelFuture future2 = bootstrap2.bind().sync();
System.out.println("Server started and listening on " + future2.channel().localAddress());
future1.channel().closeFuture().sync();
future2.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
```
在这个示例中,我们创建了两个ServerBootstrap实例,分别监听端口port1和port2。每个实例都配置了一个处理器MyServerHandler,用于处理接收到的消息。最后,我们启动服务器并等待关闭。
相关推荐
















