前言
前面我们介绍了网络一些基本的概念,虽然说这些很难吧,但是至少要做到理解吧。有了之前的基础,我们来正式揭开Netty这神秘的面纱就会简单很多。
服务端
public class PrintServer {
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); //1
EventLoopGroup workerGroup = new NioEventLoopGroup(); //2
try {
ServerBootstrap b = new ServerBootstrap(); //3
b.group(bossGroup, workerGroup) //4
.channel(NioServerSocketChannel.class) //5
.option(ChannelOption.SO_BACKLOG, 1024) //6
.childHandler(new ChannelInitializer() { //7
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new PrintServerHandler());
}
});
ChannelFuture f = b.bind(port).sync(); //8
f.channel().closeFuture().sync(); //9
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int port = 8080;
new TimeServer().bind(port);
}
}
我们来分析一下上面的这段代码(下面的每一点对应上面的注释)
1~2:首先我们创建了两个NioEventLoopGroup实例,它是一个由Netty封装好的包含NIO的线程组。为什么创建两个?我想经过前面的学习大家应该都清楚了。对,因为Netty的底层是IO多路