开启一个DiscardServer
Talk is cheap. Show me the code.
public record DiscardServer(int port) {
public void run() throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();//(1)
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();// (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)// (3)
.childHandler(new ChannelInitializer<SocketChannel>() {// (4)
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)// (5)
.childOption(ChannelOption.SO_KEEPALIVE, true);// (6)
ChannelFuture f = b.bind(port).sync();// (7)
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new DiscardServer(port).run();
}
}
- NioEventLoopGroup 是一个处理 I/O 操作的多线程事件循环。Netty 为不同类型的传输提供了各种 EventLoopGroup 实现。在这个例子中,我们正在实现一个服务器端应用程序,因此将使用两个 NioEventLoopGroup。第一个,通常称为“boss”,接受传入连接。第二个,通常称为“worker”,一旦boss接受连接并将接受的连接注册到worker,worker就会处理接受的连接的流量。使用多少线程以及它们如何映射到创建的通道取决于 EventLoopGroup 实现,甚至可以通过构造函数进行配置。
- ServerBootstrap 是一个设置服务器的辅助类。我们也可以直接使用 Channel 设置服务器。但是,这是一个乏味的过程,在大多数情况下我们不需要这样做。
- 我们指定使用 NioServerSocketChannel 类,该类用于实例化一个新的 Channel 来接受传入的连接。
- 此处指定的处理程序将始终由新接受的 Channel 评估。 ChannelInitializer 是一个特殊的处理程序,目的是帮助用户配置新的 Channel。 借此我们添加一些处理程序(例如 DiscardServerHandler)来配置新 Channel 的 ChannelPipeline 来实现您的网络应用程序。
- 设置特定于 Channel 实现的参数。 我们这个是TCP/IP 服务器,所以我们可以设置套接字选项,例如 tcpNoDelay 和 keepAlive。
- option() 用于接受传入连接的 NioServerSocketChannel。 childOption() 用于父 ServerChannel 接受的 Channels。
- 剩下的就是绑定到端口并启动服务器。 这里,我们绑定到本机的8080端口。