Netty 源码分析02 bootstrap_初始化

connect方法,调用doResolveAndConnect,连接本地地址localAddress和远程地址remoteAddress

Netty 源码分析02 bootstrap_ios_02

Netty 源码分析02 bootstrap_bootstrap_03

Netty 源码分析02 bootstrap_客户端_04

1.调用initAndRegister,初始化并且注册channel

1.1 通过channelFactory创建channel,然后调用init初始化

1.2 init初始化分成客户端bootstrap初始化和服务端serverbootstrap初始化

先看客户端

Netty 源码分析02 bootstrap_初始化_05

1.3 初始化pipeline,然后加入config的handler

1.4 设置channel选项option

1.5 设置channel的属性 attr

2.初始化好channel后,调用register注册,调用unsafe方法,本地变量registered设置为true, 并且返回一个channelPromise,

这个对象继承了channelFuture

2.1 然后在pipeline中执行fireChannelRegistered方法

2.2 然后把pipeline设置为active,激活的状态

2.3 注册后从channelFuture中,获取刚才注册好的channel

3.调用doResolveAndConnect0,开始连接。首先获取一个eventLoop

Netty 源码分析02 bootstrap_ios_06

3.1 然后获取对应的resolver解析器

3.2 使用解析器resolver,解析地址remoteAddress, 如果已经解析过了,就直接doConnect连接

3.3 解析地址,返回结果resolveFuture,然后调用doConnect连接

Netty 源码分析02 bootstrap_初始化_07

3.4 调用channel.connect连接,pipeline中的handler执行connect操作

Netty 源码分析02 bootstrap_初始化_08

Bootstrap初始化

1.创建Bootstrap对象b

2.设置使用的EventLoopGroup

3.设置要被实例化的NioSocketChannel类

4.设置可选项option

5.设置NioSocketChannel的处理器handler

6.从channel中获取ChannelPipeline,尾部加入channelHandler

7. 调用b.connect方法连接服务器,同步等待成功,也就是客户端的启动

8.f.channel().closeFuture().sync() 监听客户端关闭,并且阻塞等待


+++++++++++++++++++++++++++++++++++++++++++++++++

Netty 源码分析02 bootstrap_客户端_09

如果异步连接服务端,会返回channelFuture

如果同步连接服务端,则需要调用ChannelFuture#sync()方法

+++++++++++++++++++++++++++++++++++++++++++++++++

Netty 源码分析02 bootstrap_ios_10

Netty 源码分析02 bootstrap_ios_11