目录
1. 目标
通过io.netty.channel和io.netty.bootstrap两个package,对netty进行总体认知。进一步查看netty对NIO的封装,了解源码实现,梳理类层次关系与源码流程。
2. io.netty.channel
3. io.netty.bootstrap
3.1. AbstractBootstrap
属性
volatile EventLoopGroup group;
private volatile SocketAddress localAddress;
private final Map<ChannelOption<?>, Object> options = new LinkedHashMap<ChannelOption<?>, Object>();
private final Map<AttributeKey<?>, Object> attrs = new LinkedHashMap<AttributeKey<?>, Object>();
private volatile ChannelHandler handler;
主要方法
bind(port) /bind(host,port)
- 可见范围,public
- 供server使用
initAndRegister()
- 可见范围,package
- 流程
- newChannel 依据设置的channel class生成channel
- 调用init() [子类实现]
- group().register(channel) 由eventloopgroup选择一个eventloop,[注册channel,selector注册javachannel]。
注意点:
第一次使用eventloop(或eventloop持有thread与当前thread不一致),则调用eventloop.execute(runnable task),其会先在executor中添加selector轮询任务,然后添加task。
doBind
- 可见范围,private
- 仅server使用
abstract init(channel)
3.2. Bootstrap
what
client端,引导client channel启动
属性
继承super
主要方法
connect(host,port)
- public
- 启动方法,连接server
override init(channel)
- pipeline添加hanler
- channel设置options
- channel设置attr
doResolveAndConnect(remote,local)
- private
- 调用initAndRegister,直接或future回调中调用doResolveAndConnect0
- doResolveAndConnect0 解析remote,直接或future回调中调用doConnet
- doConnect 理解为eventloop添加任务:channel发起(outbound)connect请求
3.3. ServerBootstrap
服务器端
属性
- 继承super
- private final Map<ChannelOption<?>, Object> childOptions = new LinkedHashMap<ChannelOption<?>, Object>();
- private final Map<AttributeKey<?>, Object> childAttrs = new LinkedHashMap<AttributeKey<?>, Object>();
- private final ServerBootstrapConfig config = new ServerBootstrapConfig(this);
- private volatile EventLoopGroup childGroup;
- private volatile ChannelHandler childHandler;
主要方法
override init(channel)
- channel设置option
- channel设置attr
- channel.pipeline添加设置的handler
- channel.eventloop添加任务:pipeline.addLast(ServerBootstrapAcceptor),目的:其他设置的hanler一定放到ServerBootstrapAcceptor之前。
- ServerBootstrapAcceptor hanler channelRead
- childChannel添加childHanler
- 设置option与attr
- childGroup中选择eventloop
- 注册childChannel与selector注册childChannel
- ServerBootstrapAcceptor hanler channelRead