源碼閱讀過程當中,咱們使用下面這個簡單的示例代碼作參考;java
EventLoopGroup parentGroup = new NioEventLoopGroup(1);
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childOption(ChannelOption.TCP_NODELAY, true)
.childAttr(AttributeKey.newInstance("childAttr"), "childAttrVal")
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpServerCodec", new HttpServerCodec());
pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler());
pipeline.addLast(new LoggingHandler(LogLevel.INFO));
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
複製代碼
咱們從bind(port)開始閱讀Netty服務端的建立初始化過程算法
serverBootstrap.bind(8080)
複製代碼
順着bind方法咱們一直跟到AbstractBootStrap.doBind(final SocketAddress localAddress)promise
private ChannelFuture doBind(final SocketAddress localAddress) {
// 初始化和註冊
final ChannelFuture regFuture = initAndRegister();
...
}
複製代碼
initAndRegister()bash
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
// 建立NioServerChannel
channel = channelFactory.newChannel();
init(channel);
} catch (Throwable t) {
...
}
...
return regFuture;
}
複製代碼
建立NioServerChannel的channelFactory是什麼時候被初始化的呢?在事例代碼中對啓動引導類有以下設置:app
serverBootstrap
.channel(NioServerSocketChannel.class)
複製代碼
看下channel(Class<? extends C> channelClass)方法作了什麼socket
public B channel(Class<? extends C> channelClass) {
if (channelClass == null) {
throw new NullPointerException("channelClass");
}
// 返回一個建立channel的工廠
return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
}
複製代碼
咱們來看下ReflectiveChannelFactory類的實現ide
public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {
private final Constructor<? extends T> constructor;
public ReflectiveChannelFactory(Class<? extends T> clazz) {
ObjectUtil.checkNotNull(clazz, "clazz");
try {
// 設置傳進來的Channel的構造器
this.constructor = clazz.getConstructor();
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + StringUtil.simpleClassName(clazz) +
" does not have a public non-arg constructor", e);
}
}
@Override
public T newChannel() {
try {
// 經過構造器實例化對象
return constructor.newInstance();
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
}
}
...
}
複製代碼
跟到這咱們發現channelFactory.newChannel()實際上調用的就是NioServerSocketChannel的無參構造方法:oop
public class NioServerSocketChannel extends AbstractNioMessageChannel
implements io.netty.channel.socket.ServerSocketChannel {
....
private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();
private final ServerSocketChannelConfig config;
private static ServerSocketChannel newSocket(SelectorProvider provider) {
...
return provider.openServerSocketChannel();
...
}
public NioServerSocketChannel() {
// 1.newSocket建立ServerSocketChannel
this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}
public NioServerSocketChannel(ServerSocketChannel channel) {
// 2.調用父類構造器 賦值SelectionKey.OP_ACCEPT事件 初始化 id unsafe pipeline
super(null, channel, SelectionKey.OP_ACCEPT);
// 3.設置config
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}
...
}
複製代碼
// 設置channel和readInterestOp以及把channel設置爲非阻塞的讀
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch; // 之後javaChannel()獲取到的serverSocketChannel
this.readInterestOp = readInterestOp;
try {
ch.configureBlocking(false);
} catch (IOException e) {
...
}
}
protected AbstractChannel(Channel parent) {
this.parent = parent;
id = newId();
// netty內部的對
unsafe = newUnsafe();
pipeline = newChannelPipeline();
}
// 初始化ChannelPipeline
protected DefaultChannelPipeline(Channel channel) {
...
tail = new TailContext(this);
head = new HeadContext(this);
head.next = tail;
tail.prev = head;
...
}
複製代碼
void init(Channel channel) throws Exception {
// 1.1 設置ServerSocketChannel的options
final Map<ChannelOption<?>, Object> options = options0();
synchronized (options) {
setChannelOptions(channel, options, logger);
}
// 1.2 設置ServerSocketChannel的attrs
final Map<AttributeKey<?>, Object> attrs = attrs0();
synchronized (attrs) {
for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
@SuppressWarnings("unchecked")
AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
channel.attr(key).set(e.getValue());
}
}
ChannelPipeline p = channel.pipeline();
final EventLoopGroup currentChildGroup = childGroup;
final ChannelHandler currentChildHandler = childHandler;
final Entry<ChannelOption<?>, Object>[] currentChildOptions;
final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
// 2.1 設置childoption 如ChannelOption.TCP_NODELAY
synchronized (childOptions) {
currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
}
// 2.2 設置childAttrs
synchronized (childAttrs) {
currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
}
// 3.初始化acceptor
p.addLast(new ChannelInitializer<Channel>() {
@Override
public void initChannel(final Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
ChannelHandler handler = config.handler();
if (handler != null) {
pipeline.addLast(handler);
}
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}
});
}
複製代碼
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// 獲取到SocketChannel,也就是連結接入的客戶端Channel
final Channel child = (Channel) msg;
...
try {
// 將child註冊給其中一個childEventLoop的selector上。
childGroup.register(child).addListener(new ChannelFutureListener() {
...
});
} catch (Throwable t) {
forceClose(child, t);
}
}
複製代碼
final ChannelFuture initAndRegister() {
...
ChannelFuture regFuture = config().group().register(channel);
...
return regFuture;
}
複製代碼
private void register0(ChannelPromise promise) {
try {
...
// 1.doRegister() 調用jdk底層註冊
doRegister();
// 2.invoke HandlerAddedIfNeeded
pipeline.invokeHandlerAddedIfNeeded();
// 3.調用ServerSocketChannle的fireChannelRegistered
pipeline.fireChannelRegistered();
...
} catch (Throwable t) {
...
}
}
複製代碼
protected void doRegister() throws Exception {
...
for (;;) {
try {
// 將ServerSocketChannel註冊給selector,這塊0表明不關注任何事件,由於會在綁定的時候監聽OP_ACCEPT
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
return;
} catch (CancelledKeyException e) {
...
}
}
}
複製代碼
public final void bind(final SocketAddress localAddress, final ChannelPromise promise) {
...
// 這個時候channel並非active因此爲false
boolean wasActive = isActive();
try {
// 1.jdk ServerSocketServer綁定端口
doBind(localAddress);
} catch (Throwable t) {
...
return;
}
// 由於上邊已經完成端口綁定因此 isActive()此時爲true
if (!wasActive && isActive()) {
invokeLater(new Runnable() {
@Override
public void run() {
// 2. 一直跟蹤最後發現調用的是 HeadContext.readIfIsAutoRead()
pipeline.fireChannelActive();
}
});
}
...
}
複製代碼
public boolean isActive() {
return javaChannel().socket().isBound();
}
public boolean isBound() {
// Before 1.3 ServerSockets were always bound during creation
return bound || oldImpl;
}
複製代碼
protected void doBeginRead() throws Exception {
final SelectionKey selectionKey = this.selectionKey;
if (!selectionKey.isValid()) {
return;
}
readPending = true;
// interestOps 完成OP_ACCEPT事件綁定
final int interestOps = selectionKey.interestOps();
if ((interestOps & readInterestOp) == 0) {
selectionKey.interestOps(interestOps | readInterestOp);
}
}
複製代碼
寫到這,經過本文了解到了:ui