zoukankan      html  css  js  c++  java
  • Apache MINA NioSocketAcceptor类的实现

    NioSocketAcceptor 继承AbstractPollingIoAcceptor,实现SocketAcceptor接口

    public final class NioSocketAcceptor extends AbstractPollingIoAcceptor<NioSession, ServerSocketChannel> implements SocketAcceptor {}

    成员变量:

    private volatile Selector selector;

    volatile 修饰词的使用:http://developer.zdnet.com.cn/2007/1107/612888.shtml

    实现方法:

        @Override
        protected void init() throws Exception {
            //初始化selector 
            selector = Selector.open();
        }
     @Override
        protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
            // 创建ServerSocket通道
            ServerSocketChannel channel = ServerSocketChannel.open();
    
            boolean success = false;
    
            try {
                // 设置非阻塞的socket通道
                channel.configureBlocking(false);
    
                // 获取ServerScoket
                ServerSocket socket = channel.socket();
    
                // Set the reuseAddress flag accordingly with the setting
                socket.setReuseAddress(isReuseAddress());
    
                // 绑定监听地址和端口号
                socket.bind(localAddress, getBacklog());
    
                // 在selector中注册
                channel.register(selector, SelectionKey.OP_ACCEPT);
                success = true;
            } finally {
                if (!success) {
                    close(channel);
                }
            }
            return channel;
        }
        @Override
        protected int select() throws Exception {
            return selector.select();
        }
        @Override
        protected Iterator<ServerSocketChannel> selectedHandles() {
            return new ServerSocketChannelIterator(selector.selectedKeys());
        }
        @Override
        protected void close(ServerSocketChannel handle) throws Exception {
            SelectionKey key = handle.keyFor(selector);
    
            if (key != null) {
                key.cancel();
            }
    
            handle.close();
        }


            public ServerSocketChannel next() {
                SelectionKey key = iterator.next();
    
                if (key.isValid() && key.isAcceptable()) {
                    return (ServerSocketChannel) key.channel();
                }
    
                return null;
            }
  • 相关阅读:
    java栈的最大深度?
    String hashCode 方法为什么选择数字31作为乘子
    LinkedList 源码分析(JDK 1.8)
    ArrayList 源码分析
    LinkedHashMap 源码详细分析(JDK1.8)
    Java并发基础:了解无锁CAS就从源码分析
    IntelliJ IDEA(2018)安装详解
    HashMap 源码详细分析(JDK1.8)
    Java原子类实现原理分析
    谈谈Java中的volatile
  • 原文地址:https://www.cnblogs.com/quyongjin/p/3184471.html
Copyright © 2011-2022 走看看