这里写目录标题
Netty 源码解读
bind启动源码
我们的服务是通过下面代码进行绑定端口并启动的,所以我们从bind()方法开始分析
ChannelFuture f = b.bind(port).sync();
一直跟进到io.netty.bootstrap.AbstractBootstrap#doBind方法
private ChannelFuture doBind(final SocketAddress localAddress) {
//1 初始化和注册逻辑
final ChannelFuture regFuture = initAndRegister();
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
return regFuture;
}
if (regFuture.isDone())
ChannelPromise promise = channel.newPromise();
//2 端口绑定逻辑
doBind0(regFuture, channel, localAddress, promise);
return promise;
} else {
final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
regFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if (cause != null) {
promise.setFailure(cause);
} else {
promise.registered();
doBind0(regFuture, channel, localAddress, promise);
}
}
});
return promise;
}
}
1.初始化和注册逻辑
继续跟进initAndRegister()方法,根绝下面的注释,你类比一下Java NIO的代码,你会不会有莫名的亲切感?
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
//(1)创建ServerSocketChannel
channel = channelFactory.newChannel();
//初始化Channel,不展开说明了
init(channel);
} catch (Throwable t) {
if (channel != null)
channel.unsafe().closeForcibly();
}
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
}
//(2)注册selector
ChannelFuture regFuture = config().group().register(channel)