最近在研究tcp/ip网络通信,但一下子没有找到好的地方下手,于是就先看了看java socket通信,先从nio开始研究,但苦于网上资料都是些简单介绍,于是就直接研究Mina的源码了,废话不多少,下面开始一步一步的分析Mina的源代码
Mina版本为2.09
初始化服务端acceptor的代码如下:
IoAcceptor acceptor = new NioSocketAcceptor(); |
那么它到底做了些什么呢,我们一起来看看源代码
先贴出类图和类调用时序图,给大家看个大概:
类图:
类调用时序图:
1. 初始化NioSocketAcceptor
调用构造方法代码如下:
NioSocketAcceptor类
public NioSocketAcceptor() { super(new DefaultSocketSessionConfig(), NioProcessor.class); ((DefaultSocketSessionConfig) getSessionConfig()).init(this); } |
注意参数NioProcessor.class,这将是后面processor池中对象的具体类型
继续调用父类AbstractPollingIoAcceptor的构造方法
代码编号1.2:
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, Class<? extends IoProcessor<S>> processorClass) { this(sessionConfig, null, new SimpleIoProcessorPool<S>(processorClass), true, null); } |
注意传参new SimpleIoProcessorPool<S>(processorClass),processorClass实际是NioProcessor.class
然后继续
private AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, Executor executor, IoProcessor<S> processor, boolean createdProcessor, SelectorProvider selectorProvider) { super(sessionConfig, executor); if (processor == null) { throw new IllegalArgumentException("processor"); } //代码编号1.3:赋值给processor this.processor = processor; this.createdProcessor = createdProcessor; try { // Initialize the selector //代码编号1.4:初始化Selector init(selectorProvider); // The selector is now ready, we can switch the // flag to true so that incoming connection can be accepted 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); } } } } |
注释:
1. 代码编码1.3:赋值给AbstractPollingIoAcceptor的processor,其实际类型为SimpleIoProcessorPool
那么接下来继续看代码编号1.4
@Override protected void init(SelectorProvider selectorProvider) throws Exception { this.selectorProvider = selectorProvider; if (selectorProvider == null) { selector = Selector.open(); } else { selector = selectorProvider.openSelector(); } } |
这里初始化了selector,该selector用于注册客户端连接的事件
那么我们再画一个类图,分别看看processor和selector的位置:
2. SimpleIoProcessorPool初始化分析
从代码编号1.2红色部分点击进入
@Override
protected void init(SelectorProvider selectorProvider) throws Exception {
this.selectorProvider = selectorProvider;
if (selectorProvider == null) {
selector = Selector.open();
} else {
selector = selectorProvider.openSelector();
}
}
继续进入
public SimpleIoProcessorPool(Class<? extends IoProcessor<S>> processorType, Executor executor, int size, SelectorProvider selectorProvider) { if (processorType == null) { throw new IllegalArgumentException("processorType"); } if (size <= 0) { throw new IllegalArgumentException("size: " + size + " (expected: positive integer)"); } // Create the executor if none is provided createdExecutor = (executor == null); if (createdExecutor) { this.executor = Executors.newCachedThreadPool(); // Set a default reject handler ((ThreadPoolExecutor) this.executor).setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); } else { this.executor = executor; } //IoProcessor池,注意这里的size为电脑cpu核数+1,后面为线程的最大数 pool = new IoProcessor[size]; boolean success = false; Constructor<? extends IoProcessor<S>> processorConstructor = null; boolean usesExecutorArg = true; try { // We create at least one processor // 初始化至少一个processor,这里的processorType为NioProcessor try { try { processorConstructor = processorType.getConstructor(ExecutorService.class); pool[0] = processorConstructor.newInstance(this.executor); } catch (NoSuchMethodException e1) { // To the next step... try { if(selectorProvider==null) { processorConstructor = processorType.getConstructor(Executor.class); //Executor为线程池 pool[0] = processorConstructor.newInstance(this.executor); } else { processorConstructor = processorType.getConstructor(Executor.class, SelectorProvider.class); pool[0] = processorConstructor.newInstance(this.executor,selectorProvider); } } catch (NoSuchMethodException e2) { // To the next step... try { processorConstructor = processorType.getConstructor(); usesExecutorArg = false; pool[0] = processorConstructor.newInstance(); } catch (NoSuchMethodException e3) { // To the next step... } } } } catch (RuntimeException re) { LOGGER.error("Cannot create an IoProcessor :{}", re.getMessage()); throw re; } catch (Exception e) { String msg = "Failed to create a new instance of " + processorType.getName() + ":" + e.getMessage(); LOGGER.error(msg, e); throw new RuntimeIoException(msg, e); } if (processorConstructor == null) { // Raise an exception if no proper constructor is found. String msg = String.valueOf(processorType) + " must have a public constructor with one " + ExecutorService.class.getSimpleName() + " parameter, a public constructor with one " + Executor.class.getSimpleName() + " parameter or a public default constructor."; LOGGER.error(msg); throw new IllegalArgumentException(msg); } // Constructor found now use it for all subsequent instantiations for (int i = 1; i < pool.length; i++) { try { if (usesExecutorArg) { if(selectorProvider==null) { pool[i] = processorConstructor.newInstance(this.executor); } else { pool[i] = processorConstructor.newInstance(this.executor, selectorProvider); } } else { pool[i] = processorConstructor.newInstance(); } } catch (Exception e) { // Won't happen because it has been done previously } } success = true; } finally { if (!success) { dispose(); } } } |
注意看红色部分和中文注释部分
那么接下来