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;
            }
  • 相关阅读:
    第四章:文件stat获取函数
    第四章:文件的访问权限
    第三章:ioctl 函数详解
    第三章:fcntl 函数详解
    第四章:用户ID和组ID
    第四章:文件属性更改
    第三章:文件 I/O
    第四章:文件类型
    第二章:Unix的标准化及实现
    xml DOM解析
  • 原文地址:https://www.cnblogs.com/quyongjin/p/3184471.html
Copyright © 2011-2022 走看看