netty服务端开启多个端口
时间: 2023-07-19 11:39:26 浏览: 96
Netty 可以在一个服务端开启多个端口,可以通过创建多个 `ServerBootstrap` 对象来实现。具体步骤如下:
1. 创建两个 `EventLoopGroup` 对象,一个用于接收客户端连接,一个用于处理客户端请求。
```java
EventLoopGroup bossGroup = new NioEventLoopGroup(); // 接收客户端连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理客户端请求
```
2. 创建两个 `ServerBootstrap` 对象,分别绑定不同的端口,并设置相应的 `ChannelInitializer`。
```java
// 创建第一个 ServerBootstrap 对象
ServerBootstrap bootstrap1 = new ServerBootstrap();
bootstrap1.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(8080))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 添加 ChannelHandler 处理器
ch.pipeline().addLast(new MyChannelHandler1());
}
});
// 创建第二个 ServerBootstrap 对象
ServerBootstrap bootstrap2 = new ServerBootstrap();
bootstrap2.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(8081))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 添加 ChannelHandler 处理器
ch.pipeline().addLast(new MyChannelHandler2());
}
});
```
在这里,我们分别创建了两个 `ServerBootstrap` 对象,并分别绑定了 8080 和 8081 端口。同时,我们也设置了相应的 `ChannelInitializer`,来对客户端的请求进行处理。
3. 启动两个 `ServerBootstrap` 对象。
```java
ChannelFuture f1 = bootstrap1.bind().sync();
ChannelFuture f2 = bootstrap2.bind().sync();
```
在这里,我们分别启动了两个 `ServerBootstrap` 对象,这时候,这两个服务端就可以分别监听 8080 和 8081 端口了。
4. 关闭服务端。
```java
f1.channel().closeFuture().sync();
f2.channel().closeFuture().sync();
```
在这里,我们通过等待两个 `ChannelFuture` 对象的关闭来关闭服务端。完整的示例代码如下:
```java
EventLoopGroup bossGroup = new NioEventLoopGroup(); // 接收客户端连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理客户端请求
// 创建第一个 ServerBootstrap 对象
ServerBootstrap bootstrap1 = new ServerBootstrap();
bootstrap1.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(8080))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 添加 ChannelHandler 处理器
ch.pipeline().addLast(new MyChannelHandler1());
}
});
// 创建第二个 ServerBootstrap 对象
ServerBootstrap bootstrap2 = new ServerBootstrap();
bootstrap2.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(8081))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 添加 ChannelHandler 处理器
ch.pipeline().addLast(new MyChannelHandler2());
}
});
// 启动两个 ServerBootstrap 对象
ChannelFuture f1 = bootstrap1.bind().sync();
ChannelFuture f2 = bootstrap2.bind().sync();
// 关闭服务端
f1.channel().closeFuture().sync();
f2.channel().closeFuture().sync();
// 关闭 EventLoopGroup
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
```