一、NioSOcketConnector的初始化都干了什么。
//初始化客户端的连接类
IoConnector connector = new NioSocketConnector();
public NioSocketConnector() {
//继续看父类
super(new DefaultSocketSessionConfig(), NioProcessor.class);
((DefaultSocketSessionConfig) getSessionConfig()).init(this);
}
//父类AbstractPollingIoConnector的构造方法做了2两件事。1、调用重载的构造方法,2、生成IoProcessorPool的线程池。
protected AbstractPollingIoConnector(IoSessionConfig sessionConfig, Class<? extends IoProcessor<t>> processorClass) {
this(sessionConfig, null, new SimpleIoProcessorPool<t>(processorClass), true);
}
//重载的构造方法
private AbstractPollingIoConnector(IoSessionConfig sessionConfig, Executor executor, IoProcessor<t> processor,
boolean createdProcessor) {
//继续调用父类构造
super(sessionConfig, executor);
if (processor == null) {
throw new IllegalArgumentException("processor");
}
//设置processor,processor用于操作IoSession
this.processor = processor;
this.createdProcessor = createdProcessor;
try {
//NIO的第一步!Selector.open();
init();
selectable = true;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException("Failed to initialize.", e);
} finally {
if (!selectable) {
try {
destroy();
} catch (Exception e) {
ExceptionMonitor.getInstance().exceptionCaught(e);
}
}
}
}
//祖父类AbstractIoService
protected AbstractIoService(IoSessionConfig sessionConfig, Executor executor) {
if (sessionConfig == null) {
throw new IllegalArgumentException("sessionConfig");
}
if (getTransportMetadata() == null) {
throw new IllegalArgumentException("TransportMetadata");
}
if (!getTransportMetadata().getSessionConfigType().isAssignableFrom(sessionConfig.getClass())) {
throw new IllegalArgumentException("sessionConfig type: " + sessionConfig.getClass() + " (expected: "
+ getTransportMetadata().getSessionConfigType() + ")");
}
//生成IoServiceListenerSupport对象,该对象为IoServiceListener的辅助类,提供对IoServiceListener的增加和移除以及触发事件的操作
listeners = new IoServiceListenerSupport(this);
//添加监听对象,用于监听service的激活。
listeners.add(serviceActivationListener);
// 设置sessionConfig为DefaultSessionConfig
this.sessionConfig = sessionConfig;
ExceptionMonitor.getInstance();
//初始化线程池
if (executor == null) {
this.executor = Executors.newCachedThreadPool();
createdExecutor = true;
} else {
this.executor = executor;
createdExecutor = false;
}
threadName = getClass().getSimpleName() + '-' + id.incrementAndGet();
}
</t>
总结一下步骤1都干了什么:初始化SessionConfig,初始化IoProcessor的线程池,进行了Selector.open()操作,IoServiceListener对IoService的激活进行监听,初始化了I/O事件的线程池。具体初始化的东西后面用到,会详细讲解。