========= 本系统文章都是依据Netty的4.1.44.Final-SNAPSHOT这个版本来讲解====================
本文中关联的所有文章的总目录可以参看:系列文章目录
前言
像Netty的一些架构以及一些原理网上会有很多文章,在这里都不会再重复讲述。而我的讲解中不是上来先把整个框架中的关系图给整出来,因为这种的文章很多,这里是循序渐近的,先了一个类一个类的了解,这些类我们为什么要去了解?我们要了解类中的哪些方法?这些都是通过主入口来一步步的分析代码分析出来,当所有的关联的东西学习完后,再来总结一个总体的图形。
Netty 学习入口
一般研究框架前,肯定要找到入口,像Netty框架里面有很多测试Demo。我们首先看一个socket服务器端的代码
----------- 引用Netty框架demo中的DiscardServer的代码 -----------------
/**
* Discards any incoming data.
*/
public final class DiscardServer {
static final boolean SSL = System.getProperty("ssl") != null;
static final int PORT = Integer.parseInt(System.getProperty("port", "8009"));
public static void main(String[] args) throws Exception {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
} else {
sslCtx = null;
}
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new DiscardServerHandler());
}
});
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(PORT).sync();
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
可以看到这个端用到一些框架中的类或者接口:
NioEventLoopGroup
ServerBootstrap
NioServerSocketChannel
LoggingHandler
ChannelInitializer
DiscardServerHandler
ChannelFuture
具体这些类是做什么的?我在这里先不做一一的介绍,我会在后续的文章中进行单独的介绍