在服務(wù)端啟動過程中,設(shè)置服務(wù)端channel
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.channel(NioServerSocketChannel.class)
ServerBootstrap channel()中實現(xiàn)
public B channel(Class<? extends C> channelClass) {
return channelFactory(new ReflectiveChannelFactory<C>(
ObjectUtil.checkNotNull(channelClass, "channelClass")
));
}
創(chuàng)建channel創(chuàng)建工廠類
private final Constructor<? extends T> constructor;
public ReflectiveChannelFactory(Class<? extends T> clazz) {
ObjectUtil.checkNotNull(clazz, "clazz");
try {
this.constructor = clazz.getConstructor();
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Class " + StringUtil.simpleClassName(clazz) +
" does not have a public non-arg constructor", e);
}
}
//通過反射創(chuàng)建channel,在服務(wù)端綁定接口的時候調(diào)用
@Override
public T newChannel() {
try {
return constructor.newInstance();
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
}
}
NioServerSocketChannel構(gòu)造過程
public NioServerSocketChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}
public NioServerSocketChannel(ServerSocketChannel channel) {
//調(diào)用父類AbstractNioMessageChannel 構(gòu)造器矿瘦,并傳入對連接事件感興趣
super(null, channel, SelectionKey.OP_ACCEPT);
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}
//創(chuàng)建nio的 服務(wù)端channel
private static ServerSocketChannel newSocket(SelectorProvider provider) {
try {
/**
* Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
* {@link SelectorProvider#provider()} which is called by each ServerSocketChannel.open() otherwise.
*
* See <a >#2308</a>.
*/
return provider.openServerSocketChannel();
} catch (IOException e) {
throw new ChannelException(
"Failed to open a server socket.", e);
}
}
父類AbstractNioMessageChannel實現(xiàn)
protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
//調(diào)用父類
super(parent, ch, readInterestOp);
}
父類AbstractNioChannel 實現(xiàn)
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
//調(diào)用父類構(gòu)造器
super(parent);
設(shè)置channel
this.ch = ch;
//設(shè)置對連接事件感興趣
this.readInterestOp = readInterestOp;
try {
//設(shè)置非阻塞模式
ch.configureBlocking(false);
} catch (IOException e) {
try {
ch.close();
} catch (IOException e2) {
if (logger.isWarnEnabled()) {
logger.warn(
"Failed to close a partially initialized socket.", e2);
}
}
throw new ChannelException("Failed to enter non-blocking mode.", e);
}
}
父類 AbstractChannel 實現(xiàn)
protected AbstractChannel(Channel parent) {
//對應(yīng)服務(wù)端channel創(chuàng)建該parent為null
this.parent = parent;
//創(chuàng)建channel id
id = newId();
//創(chuàng)建netty中讀寫的unsafe類
unsafe = newUnsafe();
//創(chuàng)建channel pipeline
pipeline = newChannelPipeline();
}