《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
上篇文章中主要对Netty
启动过程中,涉及的NioEventLoopGroup
相关细节进行了详细介绍,本篇文章主要介绍启动过程中其他一些初始化步骤。
-
Channel
的创建和初始化过程 -
总结
Channel
是Netty
对于网络实现层的抽象,可以对应于JDK
中的NIO
包实现,Netty
服务端的Channel
类型是 NioServerSocketChannel
。下面来分析NioServerSocketChannel
的创建和初始化。
1、端口绑定
启动过程中重要的操作为绑定端口,而NioServerSocketChannel
的创建就是在此过程中进行的。ServerBootStrap
的bind()
方法
ChannelFuture f = b.bind(PORT).sync();
查看对应的源码,实际调用的是AbstractBootstrap
类中的bind
方法:
…
public ChannelFuture bind(int inetPort) {
return bind(new InetSocketAddress(inetPort));
}
…
public ChannelFuture bind(SocketAddress localAddress) {
validate();
return doBind(ObjectUtil.checkNotNull(localAddress, “localAddress”));
}
…
private ChannelFuture doBind(final SocketAddress localAddress) {
//初始化channel
final ChannelFuture regFuture = initAndRegister();
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
return regFuture;
}
//若注册成功,则进行bind操作
if (regFuture.isDone()) {
// At this point we know that the registration was complete and successful.
ChannelPromise promise = channel.newPromise();
doBind0(regFuture, channel, localAddress, promise);</