public class TimeServerHandler extends IoHandlerAdapter { @Override public void messageReceived(IoSession session, Object message) throws Exception { String msg = (String) message; if ("quit".equals(msg.trim())) { System.out.println("client " + session.getRemoteAddress() + " quited!"); session.close(false); return; } Date date = new Date(); session.write(date.toString()); System.out.println("message written..."); } }开启服务器
private static final int SERVER_PORT = 8888; public static void main(String[] args) throws IOException { IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("logging", new LoggingFilter()); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); acceptor.setHandler(new TimeServerHandler()); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); acceptor.getSessionConfig().setReadBufferSize(2048); acceptor.bind(new InetSocketAddress(SERVER_PORT)); }1、先创建一个IoAcceptor实例,这里创建的是一个基于tcp的Java NIO版的IoAccptor
public interface IoService { TransportMetadata getTransportMetadata(); void addListener(IoServiceListener listener); void removeListener(IoServiceListener listener); boolean isDisposing(); boolean isDisposed(); void dispose(); void dispose(boolean awaitTermination); IoHandler getHandler(); void setHandler(IoHandler handler); Map<Long, IoSession> getManagedSessions(); int getManagedSessionCount(); IoSessionConfig getSessionConfig(); IoFilterChainBuilder getFilterChainBuilder(); void setFilterChainBuilder(IoFilterChainBuilder builder); DefaultIoFilterChainBuilder getFilterChain(); boolean isActive(); long getActivationTime(); Set<WriteFuture> broadcast(Object message); IoSessionDataStructureFactory getSessionDataStructureFactory(); void setSessionDataStructureFactory(IoSessionDataStructureFactory sessionDataStructureFactory); int getScheduledWriteBytes(); int getScheduledWriteMessages(); IoServiceStatistics getStatistics(); }从接口的方法上分析可以了解到IoService的主要功能:
backlog requested maximum length of the queue of incoming connections.
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() + ")"); } listeners = new IoServiceListenerSupport(this); listeners.add(serviceActivationListener); 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(); }从AbstractIoService 构造函数来分析可以得知
public final void dispose(boolean awaitTermination) { if (disposed) { return; } synchronized (disposalLock) { if (!disposing) { disposing = true; try { dispose0(); } catch (Exception e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } if (createdExecutor) { ExecutorService e = (ExecutorService) executor; e.shutdownNow(); if (awaitTermination) { //Thread.currentThread().setName(); try { LOGGER.debug("awaitTermination on {} called by thread=[{}]", this, Thread.currentThread().getName()); e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); LOGGER.debug("awaitTermination on {} finished", this); } catch (InterruptedException e1) { LOGGER.warn("awaitTermination on [{}] was interrupted", this); // Restore the interrupted status Thread.currentThread().interrupt(); } } } disposed = true; }4、实现了broadcast
public final Set<WriteFuture> broadcast(Object message) { // Convert to Set. We do not return a List here because only the // direct caller of MessageBroadcaster knows the order of write // operations. final List<WriteFuture> futures = IoUtil.broadcast(message, getManagedSessions().values()); return new AbstractSet<WriteFuture>() { @Override public Iterator<WriteFuture> iterator() { return futures.iterator(); } @Override public int size() { return futures.size(); } }; }AbstractIoAcceptor 继承自AbstractIoService并实现了IoAcceptor接口,主要的实现有:
public final void bind(Iterable<? extends SocketAddress> localAddresses) throws IOException { if (isDisposing()) { throw new IllegalStateException("Already disposed."); } if (localAddresses == null) { throw new IllegalArgumentException("localAddresses"); } List<SocketAddress> localAddressesCopy = new ArrayList<SocketAddress>(); for (SocketAddress a: localAddresses) { checkAddressType(a); localAddressesCopy.add(a); } if (localAddressesCopy.isEmpty()) { throw new IllegalArgumentException("localAddresses is empty."); } boolean activate = false; synchronized (bindLock) { synchronized (boundAddresses) { if (boundAddresses.isEmpty()) { activate = true; } } if (getHandler() == null) { throw new IllegalStateException("handler is not set."); } try { Set<SocketAddress> addresses = bindInternal( localAddressesCopy ); synchronized (boundAddresses) { boundAddresses.addAll(addresses); } } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeIoException( "Failed to bind to: " + getLocalAddresses(), e); } } if (activate) { getListeners().fireServiceActivated(); } }5、实现了unbind的基本逻辑,更具体的逻辑在unbind0中交由子类实现
public final void unbind(Iterable<? extends SocketAddress> localAddresses) { if (localAddresses == null) { throw new IllegalArgumentException("localAddresses"); } boolean deactivate = false; synchronized (bindLock) { synchronized (boundAddresses) { if (boundAddresses.isEmpty()) { return; } List<SocketAddress> localAddressesCopy = new ArrayList<SocketAddress>(); int specifiedAddressCount = 0; for (SocketAddress a: localAddresses ) { specifiedAddressCount++; if ((a != null) && boundAddresses.contains(a) ) { localAddressesCopy.add(a); } } if (specifiedAddressCount == 0) { throw new IllegalArgumentException( "localAddresses is empty." ); } if (!localAddressesCopy.isEmpty()) { try { unbind0(localAddressesCopy); } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeIoException( "Failed to unbind from: " + getLocalAddresses(), e ); } boundAddresses.removeAll(localAddressesCopy); if (boundAddresses.isEmpty()) { deactivate = true; } } } } if (deactivate) { getListeners().fireServiceDeactivated(); } }AbstractPollingIoAcceptor<T extends AbstractIoSession, H>
private AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, Executor executor, IoProcessor<NioSession> processor, boolean createdProcessor) { super(sessionConfig, executor); if (processor == null) { throw new IllegalArgumentException("processor"); } //注入IoProcessor对象 this.processor = processor; this.createdProcessor = createdProcessor; try { //初始化设置交给子类实现 init(); // 构造函数中设置标记为true,后面便可以s 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); } } } }其他几个重载的构造函数注入默认IoProcessor为SimpleIoProcessorPool实例
protected AbstractPollingIoAcceptor(IoSessionConfig sessionConfig, Class<? extends IoProcessor<T>> processorClass, int processorCount) { this(sessionConfig, null, new SimpleIoProcessorPool<T>(processorClass, processorCount), true); }提供了一个轮询策略的Acceptor的实现
private class Acceptor implements Runnable { public void run() { // nHandles 表示已经open的ServerSocketChannel数量 int nHandles = 0; //无限循环,接收客户端的链接请求,并处理,直到所有opened ServerSocketChannel都被close while (selectable) { try { //轮询获得 int selected = select(); //open ServerSocketChannel并增加nHandles nHandles += registerHandles(); if (selected > 0) { // We have some connection request, let's process // them here. processHandles(selectedHandles()); } //close ServerSocketChannel并减少nHandles nHandles -= unregisterHandles(); //没有ServerSocketChannel在监听客户端的请求,跳出循环 if (nHandles == 0) { synchronized (lock) { if (registerQueue.isEmpty() && cancelQueue.isEmpty()) { acceptor = null; break; } } } } catch (ClosedSelectorException cse) { break; } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); try { Thread.sleep(1000); } catch (InterruptedException e1) { ExceptionMonitor.getInstance().exceptionCaught(e1); } } } if (selectable && isDisposing()) { selectable = false; try { if (createdProcessor) { processor.dispose(); } } finally { try { synchronized (disposalLock) { if (isDisposing()) { destroy(); } } } catch (Exception e) { ExceptionMonitor.getInstance().exceptionCaught(e); } finally { disposalFuture.setDone(); } } } } private void processHandles(Iterator<ServerSocketChannel> handles) throws Exception { while (handles.hasNext()) { ServerSocketChannel handle = handles.next(); handles.remove(); // 接收客户端的请求,建立链接,返回对链接信息封装后的IoSession NioSession session = accept(processor, handle); if (session == null) { break; } // 初始化IoSession信息 initSession(session, null, null); // 将连接的I/O(read,write,close etc)交给Processor线程处理 session.getProcessor().add(session); } } } private int registerHandles() { //开启一个无限循环,不断从registerQueue队列中获取AcceptorOperationFuture,直到registerQueue为空 for (;;) { AcceptorOperationFuture future = registerQueue.poll(); if (future == null) { return 0; } // 创建一个临时的map以便在打开socket的时候出现异常及时释放资源 Map<SocketAddress, ServerSocketChannel> newHandles = new ConcurrentHashMap<SocketAddress, ServerSocketChannel>(); List<SocketAddress> localAddresses = future.getLocalAddresses(); try { for (SocketAddress a : localAddresses) { //遍历所有的SocketAddress,open ServerSocketChannel ServerSocketChannel handle = open(a); newHandles.put(localAddress(handle), handle); } // 未出现异常,将所有open成功的ServerSocketChannel放到boundHandles boundHandles.putAll(newHandles); // 设置异步处理完成 future.setDone(); // 返回open成功的ServerSocketChannel的数量 return newHandles.size(); } catch (Exception e) { future.setException(e); } finally { //在open时出现了异常,释放相应的 资源 if (future.getException() != null) { for (ServerSocketChannel handle : newHandles.values()) { try { close(handle); } catch (Exception e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } wakeup(); } } } } // 关闭ServerSocketChannel private int unregisterHandles() { int cancelledHandles = 0; // 循环从cancelQueue队列中获取待关闭的ServerSocketChannel,直到cancelQueue清空 for (;;) { AcceptorOperationFuture future = cancelQueue.poll(); if (future == null) { break; } for (SocketAddress a : future.getLocalAddresses()) { // 先从已绑定的ServerSocketChannel列表中移除 ServerSocketChannel handle = boundHandles.remove(a); if (handle == null) { continue; } try { //关闭ServerSocketChannel,真正的实现交给子类 close(handle); wakeup(); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } finally { cancelledHandles++; } } // future.setDone(); } //返回已关闭的ServerSocketChannel的数量 return cancelledHandles; }NioSocketAcceptor
//默认的ServerSocket的backlog属性为50 private int backlog = 50; // 默认reuseAddress为false private boolean reuseAddress = false; // java nio 中的selector,状态改变多线程可见 private volatile Selector selector; //构造函数出入的默认IoSessionConfig实现为DefaultSocketSessionConfig public NioSocketAcceptor() { super(new DefaultSocketSessionConfig(), NioProcessor.class); ((DefaultSocketSessionConfig) getSessionConfig()).init(this); } // 如果你熟悉java nio,看到这些代码是否有种豁然开朗的感觉呢?原来是这样的啊! @Override protected void init() throws Exception { selector = Selector.open(); } @Override protected void destroy() throws Exception { if (selector != null) { selector.close(); } } public TransportMetadata getTransportMetadata() { return NioSocketSession.METADATA; } @Override protected NioSession accept(IoProcessor<NioSession> processor, ServerSocketChannel handle) throws Exception { SelectionKey key = handle.keyFor(selector); if ((key == null) || (!key.isValid()) || (!key.isAcceptable()) ) { return null; } SocketChannel ch = handle.accept(); if (ch == null) { return null; } return new NioSocketSession(this, processor, ch); } @Override protected ServerSocketChannel open(SocketAddress localAddress) throws Exception { // Creates the listening ServerSocket ServerSocketChannel channel = ServerSocketChannel.open(); boolean success = false; try { // This is a non blocking socket channel channel.configureBlocking(false); // Configure the server socket, ServerSocket socket = channel.socket(); // Set the reuseAddress flag accordingly with the setting socket.setReuseAddress(isReuseAddress()); // and bind. socket.bind(localAddress, getBacklog()); // Register the channel within the selector for ACCEPT event channel.register(selector, SelectionKey.OP_ACCEPT); success = true; } finally { if (!success) { close(channel); } } return channel; } @Override protected void close(ServerSocketChannel handle) throws Exception { SelectionKey key = handle.keyFor(selector); if (key != null) { key.cancel(); } handle.close(); } @Override protected void wakeup() { selector.wakeup(); }