在服务端启动过程中,设置服务端channel
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.channel(NioServerSocketChannel.class)
ServerBootstrap channel()中实现
public B channel(Class<? extends C> channelClass) {
return channelFactory(new ReflectiveChannelFactory<C>(
ObjectUtil.checkNotNull(channelClass, "channelClass")
));
}
创建channel创建工厂类
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);
}
}
//通过反射创建channel,在服务端绑定接口的时候调用
@Override
public T newChannel() {
try {
return constructor.newInstance();
} catch (Throwable t) {
throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
}
}
NioServerSocketChannel构造过程
public NioServerSocketChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}
public NioServerSocketChannel(ServerSocketChannel channel) {
//调用父类AbstractNioMessageChannel 构造器,并传入对连接事件感兴趣
super(null, channel, SelectionKey.OP_ACCEPT);
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}
//创建nio的 服务端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 href="https://github.com/netty/netty/issues/2308">#2308</a>.
*/
return provider.openServerSocketChannel();
} catch (IOException e) {
throw new ChannelException(
"Failed to open a server socket.", e);
}
}
父类AbstractNioMessageChannel实现
protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
//调用父类
super(parent, ch, readInterestOp);
}
父类AbstractNioChannel 实现
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
//调用父类构造器
super(parent);
设置channel
this.ch = ch;
//设置对连接事件感兴趣
this.readInterestOp = readInterestOp;
try {
//设置非阻塞模式
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 实现
protected AbstractChannel(Channel parent) {
//对应服务端channel创建该parent为null
this.parent = parent;
//创建channel id
id = newId();
//创建netty中读写的unsafe类
unsafe = newUnsafe();
//创建channel pipeline
pipeline = newChannelPipeline();
}
网友评论