//初始化io處理事件/**
* Set the {@link ChannelHandler} which is used to serve the request for the {@link Channel}'s.
*/public ServerBootstrap childHandler(ChannelHandler childHandler) {
if (childHandler == null) {
thrownew NullPointerException("childHandler");
}
this.childHandler = childHandler;
returnthis;
}
bind(開啓服務類)
//綁定端口public ChannelFuture bind(SocketAddress localAddress) {
validate(); //參數校驗 是否先實現初始化if (localAddress == null) {
thrownew NullPointerException("localAddress");
}
return doBind(localAddress);
}
// 真正的開啓服務private ChannelFuture doBind(final SocketAddress localAddress) {
final ChannelFuture regFuture = initAndRegister();
final Channel channel = regFuture.channel();
if (regFuture.cause() != null) {
return regFuture;
}
if (regFuture.isDone()) {
// At this point we know that the registration was complete and successful.
ChannelPromise promise = channel.newPromise();
doBind0(regFuture, channel, localAddress, promise);
return promise;
} else {
// Registration future is almost always fulfilled already, but just in case it's not.final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
regFuture.addListener(new ChannelFutureListener() {
@OverridepublicvoidoperationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if (cause != null) {
// Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an// IllegalStateException once we try to access the EventLoop of the Channel.
promise.setFailure(cause);
} else {
// Registration was successful, so set the correct executor to use.// See https://github.com/netty/netty/issues/2586
promise.executor = channel.eventLoop();
}
doBind0(regFuture, channel, localAddress, promise);
}
});
return promise;
}
initAndRegister
//
final ChannelFuture initAndRegister() {
final Channel channel = channelFactory().newChannel(); // 由前面初始化的channel反射工廠獲取channel(NioServerSocketChannel)try {
init(channel);
} catch (Throwable t) {
channel.unsafe().closeForcibly();
// as the Channel is not registered yet we need to force the usage of the GlobalEventExecutorreturnnew DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
}
ChannelFuture regFuture = group().register(channel);
if (regFuture.cause() != null) {
if (channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
}
return regFuture;
}