Java 类java.nio.channels.spi.SelectorProvider 实例源码

项目:nuls    文件:ConnectionManager.java   
/**
 * open the serverSocketChannel and register accept action
 */
public void init() {
    lock.lock();
    try {
        if (!running) {
            selector = SelectorProvider.provider().openSelector();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(network.port()));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }
    } catch (IOException e) {
        serverClose();
        throw new NulsRuntimeException(ErrorCode.NET_SERVER_START_ERROR, e);
    } finally {
        lock.unlock();
    }
}
项目:jdk8u-jdk    文件:NullTest.java   
public static void main(String args[]) {

        // test the assertion that SelectorProvider.inheritedChannel()
        // and System.inheritedChannel return null when standard input
        // is not connected to a socket

        Channel c1, c2;
        try {
            c1 = SelectorProvider.provider().inheritedChannel();
            c2 = System.inheritedChannel();
        } catch (IOException ioe) {
            throw new RuntimeException("Unexpected IOException: " + ioe);
        }
        if (c1 != null || c2 != null) {
            throw new RuntimeException("Channel returned - unexpected");
        }
    }
项目:openjdk-jdk10    文件:NullTest.java   
public static void main(String args[]) {

        // test the assertion that SelectorProvider.inheritedChannel()
        // and System.inheritedChannel return null when standard input
        // is not connected to a socket

        Channel c1, c2;
        try {
            c1 = SelectorProvider.provider().inheritedChannel();
            c2 = System.inheritedChannel();
        } catch (IOException ioe) {
            throw new RuntimeException("Unexpected IOException: " + ioe);
        }
        if (c1 != null || c2 != null) {
            throw new RuntimeException("Channel returned - unexpected");
        }
    }
项目:jdk8u-jdk    文件:EmptyRead.java   
public static void main(String[] args) throws Exception {
    SelectorProvider sp = SelectorProvider.provider();
    Pipe p = sp.openPipe();
    Pipe.SinkChannel sink = p.sink();
    Pipe.SourceChannel source = p.source();

    byte[] someBytes = new byte[0];
    ByteBuffer outgoingdata = ByteBuffer.wrap(someBytes);

    int totalWritten = 0;
    int written = sink.write(outgoingdata);
    if (written < 0)
        throw new Exception("Write failed");

    ByteBuffer incomingdata = ByteBuffer.allocateDirect(0);
    int read = source.read(incomingdata);
    if (read < 0)
        throw new Exception("Read EOF");

    sink.close();
    source.close();
}
项目:openjdk-jdk10    文件:Open.java   
public static void main(String[] args) throws Exception {

        // Load necessary classes ahead of time
        DatagramChannel dc = DatagramChannel.open();
        Exception se = new SocketException();
        SelectorProvider sp = SelectorProvider.provider();
        Pipe p = sp.openPipe();
        ServerSocketChannel ssc = ServerSocketChannel.open();

        test1();
        test2();
        test3();
        test4();
    }
项目:openjdk-jdk10    文件:EmptyRead.java   
public static void main(String[] args) throws Exception {
    SelectorProvider sp = SelectorProvider.provider();
    Pipe p = sp.openPipe();
    Pipe.SinkChannel sink = p.sink();
    Pipe.SourceChannel source = p.source();

    byte[] someBytes = new byte[0];
    ByteBuffer outgoingdata = ByteBuffer.wrap(someBytes);

    int totalWritten = 0;
    int written = sink.write(outgoingdata);
    if (written < 0)
        throw new Exception("Write failed");

    ByteBuffer incomingdata = ByteBuffer.allocateDirect(0);
    int read = source.read(incomingdata);
    if (read < 0)
        throw new Exception("Read EOF");

    sink.close();
    source.close();
}
项目:jdk8u-jdk    文件:SctpChannelImpl.java   
/**
 * Constructor for sockets obtained from branching
 */
public SctpChannelImpl(SelectorProvider provider,
                       FileDescriptor fd,
                       Association association)
        throws IOException {
    super(provider);
    this.fd = fd;
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.CONNECTED;
    port = (Net.localAddress(fd)).getPort();

    if (association != null) { /* branched */
        this.association = association;
    } else { /* obtained from server channel */
        /* Receive COMM_UP */
        ByteBuffer buf = Util.getTemporaryDirectBuffer(50);
        try {
            receive(buf, null, null, true);
        } finally {
            Util.releaseTemporaryDirectBuffer(buf);
        }
    }
}
项目:openjdk-jdk10    文件:SctpMultiChannelImpl.java   
public SctpMultiChannelImpl(SelectorProvider provider)
        throws IOException {
    //TODO: update provider, remove public modifier
    super(provider);
    this.fd = SctpNet.socket(false /*one-to-many*/);
    this.fdVal = IOUtil.fdVal(fd);
}
项目:creacoinj    文件:NioServer.java   
/**
 * Creates a new server which is capable of listening for incoming connections and processing client provided data
 * using {@link StreamConnection}s created by the given {@link StreamConnectionFactory}
 *
 * @throws IOException If there is an issue opening the server socket or binding fails for some reason
 */
public NioServer(final StreamConnectionFactory connectionFactory, InetSocketAddress bindAddress) throws IOException {
    this.connectionFactory = connectionFactory;

    sc = ServerSocketChannel.open();
    sc.configureBlocking(false);
    sc.socket().bind(bindAddress);
    selector = SelectorProvider.provider().openSelector();
    sc.register(selector, SelectionKey.OP_ACCEPT);
}
项目:creacoinj    文件:NioClientManager.java   
/**
 * Creates a new client manager which uses Java NIO for socket management. Uses a single thread to handle all select
 * calls.
 */
public NioClientManager() {
    try {
        selector = SelectorProvider.provider().openSelector();
    } catch (IOException e) {
        throw new RuntimeException(e); // Shouldn't ever happen
    }
}
项目:okwallet    文件:NioClientManager.java   
/**
 * Creates a new client manager which uses Java NIO for socket management. Uses a single thread to handle all select
 * calls.
 */
public NioClientManager() {
    try {
        selector = SelectorProvider.provider().openSelector();
    } catch (IOException e) {
        throw new RuntimeException(e); // Shouldn't ever happen
    }
}
项目:Jupiter    文件:RCONServer.java   
public RCONServer(String address, int port, String password) throws IOException {
    this.setName("RCON");
    this.running = true;

    this.serverChannel = ServerSocketChannel.open();
    this.serverChannel.configureBlocking(false);
    this.serverChannel.socket().bind(new InetSocketAddress(address, port));

    this.selector = SelectorProvider.provider().openSelector();
    this.serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);

    this.password = password;
}
项目:spark_deep    文件:SocketIOWithTimeout.java   
/**
 * Takes one selector from end of LRU list of free selectors.
 * If there are no selectors awailable, it creates a new selector.
 * Also invokes trimIdleSelectors(). 
 * 
 * @param channel
 * @return 
 * @throws IOException
 */
private synchronized SelectorInfo get(SelectableChannel channel) 
                                                     throws IOException {
  SelectorInfo selInfo = null;

  SelectorProvider provider = channel.provider();

  // pick the list : rarely there is more than one provider in use.
  ProviderInfo pList = providerList;
  while (pList != null && pList.provider != provider) {
    pList = pList.next;
  }      
  if (pList == null) {
    //LOG.info("Creating new ProviderInfo : " + provider.toString());
    pList = new ProviderInfo();
    pList.provider = provider;
    pList.queue = new LinkedList<SelectorInfo>();
    pList.next = providerList;
    providerList = pList;
  }

  LinkedList<SelectorInfo> queue = pList.queue;

  if (queue.isEmpty()) {
    Selector selector = provider.openSelector();
    selInfo = new SelectorInfo();
    selInfo.selector = selector;
    selInfo.queue = queue;
  } else {
    selInfo = queue.removeLast();
  }

  trimIdleSelectors(System.currentTimeMillis());
  return selInfo;
}
项目:jdk8u-jdk    文件:IsConnectable.java   
static void test(TestServers.DayTimeServer daytimeServer) throws Exception {
    InetSocketAddress isa
        = new InetSocketAddress(daytimeServer.getAddress(),
                                daytimeServer.getPort());
    SocketChannel sc = SocketChannel.open();
    sc.configureBlocking(false);
    final boolean immediatelyConnected = sc.connect(isa);

    Selector selector = SelectorProvider.provider().openSelector();
    try {
        SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
        int keysAdded = selector.select();
        if (keysAdded > 0) {
            boolean result = sc.finishConnect();
            if (result) {
                keysAdded = selector.select(5000);
                // 4750573: keysAdded should not be incremented when op is dropped
                // from a key already in the selected key set
                if (keysAdded > 0)
                    throw new Exception("Test failed: 4750573 detected");
                Set<SelectionKey> sel = selector.selectedKeys();
                Iterator<SelectionKey> i = sel.iterator();
                SelectionKey sk = i.next();
                // 4737146: isConnectable should be false while connected
                if (sk.isConnectable())
                    throw new Exception("Test failed: 4737146 detected");
            }
        } else {
            if (!immediatelyConnected) {
                throw new Exception("Select failed");
            } else {
                System.out.println("IsConnectable couldn't be fully tested for "
                        + System.getProperty("os.name"));
            }
        }
    } finally {
        sc.close();
        selector.close();
    }
}
项目:openjdk-jdk10    文件:SctpChannelImpl.java   
/**
 * Constructor for normal connecting sockets
 */
public SctpChannelImpl(SelectorProvider provider) throws IOException {
    //TODO: update provider remove public modifier
    super(provider);
    this.fd = SctpNet.socket(true);
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.UNCONNECTED;
}
项目:openjdk-jdk10    文件:SctpServerChannelImpl.java   
/**
 * Initializes a new instance of this class.
 */
public SctpServerChannelImpl(SelectorProvider provider)
        throws IOException {
    //TODO: update provider remove public modifier
    super(provider);
    this.fd = SctpNet.socket(true);
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.INUSE;
}
项目:openjdk-jdk10    文件:WindowsSelectorImpl.java   
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
    super(sp);
    pollWrapper = new PollArrayWrapper(INIT_CAP);
    wakeupPipe = Pipe.open();
    wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal();

    // Disable the Nagle algorithm so that the wakeup is more immediate
    SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink();
    (sink.sc).socket().setTcpNoDelay(true);
    wakeupSinkFd = ((SelChImpl)sink).getFDVal();

    pollWrapper.addWakeupSocket(wakeupSourceFd, 0);
}
项目:openjdk-jdk10    文件:SelectorImpl.java   
protected SelectorImpl(SelectorProvider sp) {
    super(sp);
    keys = new HashSet<>();
    selectedKeys = new HashSet<>();
    publicKeys = Collections.unmodifiableSet(keys);
    publicSelectedKeys = Util.ungrowableSet(selectedKeys);
}
项目:okwallet    文件:NioServer.java   
/**
 * Creates a new server which is capable of listening for incoming connections and processing client provided data
 * using {@link StreamConnection}s created by the given {@link StreamConnectionFactory}
 *
 * @throws IOException If there is an issue opening the server socket or binding fails for some reason
 */
public NioServer(final StreamConnectionFactory connectionFactory, InetSocketAddress bindAddress) throws IOException {
    this.connectionFactory = connectionFactory;

    sc = ServerSocketChannel.open();
    sc.configureBlocking(false);
    sc.socket().bind(bindAddress);
    selector = SelectorProvider.provider().openSelector();
    sc.register(selector, SelectionKey.OP_ACCEPT);
}
项目:OpenJSharp    文件:InheritedChannel.java   
InheritedSocketChannelImpl(SelectorProvider sp,
                           FileDescriptor fd,
                           InetSocketAddress remote)
    throws IOException
{
    super(sp, fd, remote);
}
项目:OpenJSharp    文件:SctpMultiChannelImpl.java   
public SctpMultiChannelImpl(SelectorProvider provider)
        throws IOException {
    //TODO: update provider, remove public modifier
    super(provider);
    this.fd = SctpNet.socket(false /*one-to-many*/);
    this.fdVal = IOUtil.fdVal(fd);
}
项目:OpenJSharp    文件:SctpServerChannelImpl.java   
/**
 * Initializes a new instance of this class.
 */
public SctpServerChannelImpl(SelectorProvider provider)
        throws IOException {
    //TODO: update provider remove public modifier
    super(provider);
    this.fd = SctpNet.socket(true);
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.INUSE;
}
项目:OpenJSharp    文件:SctpChannelImpl.java   
/**
 * Constructor for normal connecting sockets
 */
public SctpChannelImpl(SelectorProvider provider) throws IOException {
    //TODO: update provider remove public modifier
    super(provider);
    this.fd = SctpNet.socket(true);
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.UNCONNECTED;
}
项目:OpenJSharp    文件:DefaultSelectorProvider.java   
/**
 * Returns the default SelectorProvider.
 */
public static SelectorProvider create() {
    return new SelectorProviderImpl() {
        public AbstractSelector openSelector() throws IOException {
            return new DotNetSelectorImpl(this);
        }
    };
}
项目:Jenisys3    文件:RCONServer.java   
public RCONServer(String address, int port, String password) throws IOException {
    this.setName("RCON");
    this.running = true;

    this.serverChannel = ServerSocketChannel.open();
    this.serverChannel.configureBlocking(false);
    this.serverChannel.socket().bind(new InetSocketAddress(address, port));

    this.selector = SelectorProvider.provider().openSelector();
    this.serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);

    this.password = password;
}
项目:kcp-netty    文件:UkcpClientUdpChannel.java   
private static DatagramChannel newSocket(SelectorProvider provider) {
    try {
        /**
         *  Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
         *  {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
         *
         *  See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
         */
        return provider.openDatagramChannel();
    } catch (IOException e) {
        throw new ChannelException("Failed to open a socket.", e);
    }
}
项目:kcp-netty    文件:UkcpServerChannel.java   
private static DatagramChannel newSocket(SelectorProvider provider) {
    try {
        /**
         *  Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
         *  {@link SelectorProvider#provider()} which is called by each DatagramChannel.open() otherwise.
         *
         *  See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
         */
        return provider.openDatagramChannel();
    } catch (IOException e) {
        throw new ChannelException("Failed to open a socket.", e);
    }
}
项目:boohee_v5.6    文件:WebSocketClient.java   
public WebSocketClient(URI serverUri, Draft draft, Map<String, String> headers, int connecttimeout) {
    this.uri = null;
    this.conn = null;
    this.channel = null;
    this.wrappedchannel = null;
    this.connectLatch = new CountDownLatch(1);
    this.closeLatch = new CountDownLatch(1);
    this.timeout = 0;
    this.wsfactory = new DefaultWebSocketClientFactory(this);
    this.proxyAddress = null;
    if (serverUri == null) {
        throw new IllegalArgumentException();
    } else if (draft == null) {
        throw new IllegalArgumentException("null as draft is permitted for `WebSocketServer` only!");
    } else {
        this.uri = serverUri;
        this.draft = draft;
        this.headers = headers;
        this.timeout = connecttimeout;
        try {
            this.channel = SelectorProvider.provider().openSocketChannel();
            this.channel.configureBlocking(true);
        } catch (IOException e) {
            this.channel = null;
            onWebsocketError(null, e);
        }
        if (this.channel == null) {
            this.conn = (WebSocketImpl) this.wsfactory.createWebSocket((WebSocketAdapter) this, draft, null);
            this.conn.close(-1, "Failed to create or configure SocketChannel.");
            return;
        }
        this.conn = (WebSocketImpl) this.wsfactory.createWebSocket((WebSocketAdapter) this, draft, this.channel.socket());
    }
}
项目:hadoop    文件:SocketIOWithTimeout.java   
/**
 * Takes one selector from end of LRU list of free selectors.
 * If there are no selectors awailable, it creates a new selector.
 * Also invokes trimIdleSelectors(). 
 * 
 * @param channel
 * @return 
 * @throws IOException
 */
private synchronized SelectorInfo get(SelectableChannel channel) 
                                                     throws IOException {
  SelectorInfo selInfo = null;

  SelectorProvider provider = channel.provider();

  // pick the list : rarely there is more than one provider in use.
  ProviderInfo pList = providerList;
  while (pList != null && pList.provider != provider) {
    pList = pList.next;
  }      
  if (pList == null) {
    //LOG.info("Creating new ProviderInfo : " + provider.toString());
    pList = new ProviderInfo();
    pList.provider = provider;
    pList.queue = new LinkedList<SelectorInfo>();
    pList.next = providerList;
    providerList = pList;
  }

  LinkedList<SelectorInfo> queue = pList.queue;

  if (queue.isEmpty()) {
    Selector selector = provider.openSelector();
    selInfo = new SelectorInfo();
    selInfo.selector = selector;
    selInfo.queue = queue;
  } else {
    selInfo = queue.removeLast();
  }

  trimIdleSelectors(Time.now());
  return selInfo;
}
项目:CoreX    文件:RCONServer.java   
public RCONServer(String address, int port, String password) throws IOException {
    this.setName("RCON");
    this.running = true;

    this.serverChannel = ServerSocketChannel.open();
    this.serverChannel.configureBlocking(false);
    this.serverChannel.socket().bind(new InetSocketAddress(address, port));

    this.selector = SelectorProvider.provider().openSelector();
    this.serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);

    this.password = password;
}
项目:jdk8u-jdk    文件:PipeChannel.java   
public static void main(String[] args) throws Exception {
    for (int x=0; x<100; x++) {
        SelectorProvider sp = SelectorProvider.provider();
        Pipe p = sp.openPipe();
        Pipe.SinkChannel sink = p.sink();
        Pipe.SourceChannel source = p.source();

        ByteBuffer outgoingdata = ByteBuffer.allocateDirect(10);
        byte[] someBytes = new byte[10];
        generator.nextBytes(someBytes);
        outgoingdata.put(someBytes);
        outgoingdata.flip();

        int totalWritten = 0;
        while (totalWritten < 10) {
            int written = sink.write(outgoingdata);
            if (written < 0)
                throw new Exception("Write failed");
            totalWritten += written;
        }

        ByteBuffer incomingdata = ByteBuffer.allocateDirect(10);
        int totalRead = 0;
        do {
            int bytesRead = source.read(incomingdata);
            if (bytesRead > 0)
                totalRead += bytesRead;
        } while(totalRead < 10);

        for(int i=0; i<10; i++)
            if (outgoingdata.get(i) != incomingdata.get(i))
                throw new Exception("Pipe failed");
        sink.close();
        source.close();
    }
}
项目:jdk8u-jdk    文件:InheritedChannel.java   
InheritedSocketChannelImpl(SelectorProvider sp,
                           FileDescriptor fd,
                           InetSocketAddress remote)
    throws IOException
{
    super(sp, fd, remote);
}
项目:jdk8u-jdk    文件:SctpMultiChannelImpl.java   
public SctpMultiChannelImpl(SelectorProvider provider)
        throws IOException {
    //TODO: update provider, remove public modifier
    super(provider);
    this.fd = SctpNet.socket(false /*one-to-many*/);
    this.fdVal = IOUtil.fdVal(fd);
}
项目:jdk8u-jdk    文件:SctpServerChannelImpl.java   
/**
 * Initializes a new instance of this class.
 */
public SctpServerChannelImpl(SelectorProvider provider)
        throws IOException {
    //TODO: update provider remove public modifier
    super(provider);
    this.fd = SctpNet.socket(true);
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.INUSE;
}
项目:jdk8u-jdk    文件:SctpChannelImpl.java   
/**
 * Constructor for normal connecting sockets
 */
public SctpChannelImpl(SelectorProvider provider) throws IOException {
    //TODO: update provider remove public modifier
    super(provider);
    this.fd = SctpNet.socket(true);
    this.fdVal = IOUtil.fdVal(fd);
    this.state = ChannelState.UNCONNECTED;
}
项目:openjdk-jdk10    文件:IsConnectable.java   
static void test(TestServers.DayTimeServer daytimeServer) throws Exception {
    InetSocketAddress isa
        = new InetSocketAddress(daytimeServer.getAddress(),
                                daytimeServer.getPort());
    SocketChannel sc = SocketChannel.open();
    sc.configureBlocking(false);
    final boolean immediatelyConnected = sc.connect(isa);

    Selector selector = SelectorProvider.provider().openSelector();
    try {
        SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
        int keysAdded = selector.select();
        if (keysAdded > 0) {
            boolean result = sc.finishConnect();
            if (result) {
                keysAdded = selector.select(5000);
                // 4750573: keysAdded should not be incremented when op is dropped
                // from a key already in the selected key set
                if (keysAdded > 0)
                    throw new Exception("Test failed: 4750573 detected");
                Set<SelectionKey> sel = selector.selectedKeys();
                Iterator<SelectionKey> i = sel.iterator();
                SelectionKey sk = i.next();
                // 4737146: isConnectable should be false while connected
                if (sk.isConnectable())
                    throw new Exception("Test failed: 4737146 detected");
            }
        } else {
            if (!immediatelyConnected) {
                throw new Exception("Select failed");
            } else {
                System.out.println("IsConnectable couldn't be fully tested for "
                        + System.getProperty("os.name"));
            }
        }
    } finally {
        sc.close();
        selector.close();
    }
}
项目:openjdk-jdk10    文件:DefaultSelectorProvider.java   
/**
 * Returns the default SelectorProvider.
 */
public static SelectorProvider create() {
    return new EPollSelectorProvider();
}
项目:LearningOfThinkInJava    文件:MultiThreadNIOEchoServer.java   
private void startServer() throws Exception{
        //声明一个selector
        selector= SelectorProvider.provider().openSelector();

        //声明一个server socket channel,而且是非阻塞的。
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);

//        InetSocketAddress isa=new InetSocketAddress(InetAddress.getLocalHost(),8000);
        //声明服务器端的端口
        InetSocketAddress isa=new InetSocketAddress(8000);
        //服务器端的socket channel绑定在这个端口。
        ssc.socket().bind(isa);
        //把一个socketchannel注册到一个selector上,同时选择监听的事件,SelectionKey.OP_ACCEPT表示对selector如果
        //监听到注册在它上面的server socket channel准备去接受一个连接,或 有个错误挂起,selector将把OP_ACCEPT加到
        //key ready set 并把key加到selected-key set.
        SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);

        for(;;){
            selector.select();
            Set readyKeys=selector.selectedKeys();
            Iterator i=readyKeys.iterator();
            long e=0;
            while (i.hasNext()){
                SelectionKey sk=(SelectionKey)i.next();
                i.remove();

                if(sk.isAcceptable()){
                    doAccept(sk);
                }else if(sk.isValid()&&sk.isReadable()){
                    if(!geym_time_stat.containsKey(((SocketChannel)sk.channel()).socket())){
                        geym_time_stat.put(((SocketChannel)sk.channel()).socket(),System.currentTimeMillis());
                        doRead(sk);
                    }
                }else if(sk.isValid()&&sk.isWritable()){
                    doWrite(sk);
                    e=System.currentTimeMillis();
                    long b=geym_time_stat.remove(((SocketChannel)sk.channel()).socket());
                    System.out.println("spend"+(e-b)+"ms");
                }
            }
        }
    }
项目:mysql-protocol    文件:Multiplexer.java   
public Multiplexer() throws IOException {
    this.selector = SelectorProvider.provider().openSelector();
}
项目:multithread    文件:NIOEchoServer.java   
/**
 * 用于启动NIO Server
 */
private void startServer() throws Exception {
    //通过工厂方法获得一个Selector对象的实例
    selector = SelectorProvider.provider().openSelector();
    //获得表示服务端的SocketChannel实例
    ServerSocketChannel ssc = ServerSocketChannel.open();
    //将这个SocketChannel设置为非阻塞模式。实际上,Channel也可以像传统的Socket那样按照阻塞的方式工作
    //但在这里,更倾向于让其工作在非阻塞模式,在这种模式下,我们才可以向Channel注册感兴趣的事件,并且在数据准备好时,得到必要的通知
    ssc.configureBlocking(false);
    //将Channel绑定在8000端口。
    InetSocketAddress isa = new InetSocketAddress(/*InetAddress.getLocalHost()*/"localhost", 8000);
    ssc.socket().bind(isa);
    //将ServerSocketChannel绑定到Selector上,并注册它感兴趣的事件为Accept
    //当Selector发现ServerSocketChannel有新的客户端连接时,就会通知ServerSocketChannel进行处理。
    //方法register()的返回值是一个SelectionKey,SelectionKey表示一对Selector和Channel的关系。
    //当Channel注册到Selector上时,就相当于确立了两者的服务关系,那么SelectionKey就是这个契约。
    //当Selector或者Channel被关闭时,它们对应的SelectionKey就会失效。
    SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
    //无穷循环,它的主要任务就是等待-分发网络消息
    for (; ; ) {
        //select()方法是一个阻塞方法。如果当前没有任何数据准备好,它就会等待。一旦有数据可读,它就会返回。它的返回值是已经准备就绪的SelectionKey的数量。
        selector.select();
        //获取那些准备好的SelectionKey
        Set readyKeys = selector.selectedKeys();
        Iterator i = readyKeys.iterator();
        long e = 0;
        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            //将这个元素移除!注意,这个非常重要,否则就会重复处理相同的SelectionKey
            i.remove();
            //判断当前SelectionKey所代表的Channel是否在Acceptable状态,如果是,就进行客户端的接收(执行doAccept()方法)
            if (sk.isAcceptable()) {
                doAccept(sk);
                //判断Channel是否已经可以读了,如果是就进行读取(doRead()方法)
            } else if (sk.isValid() && sk.isReadable()) {
                if (!time_stat.containsKey(((SocketChannel) sk.channel()).socket()))
                    time_stat.put(((SocketChannel) sk.channel()).socket(), System.currentTimeMillis());
                doRead(sk);
                //判断通道是否准备好进行写。如果是就进行写入(doWrite()方法),同时在写入完成后,根据读取前的时间戳,输出处理这个Socket连接的耗时。
            } else if (sk.isValid() && sk.isWritable()) {

                doWrite(sk);
                e = System.currentTimeMillis();
                long b = time_stat.remove(((SocketChannel) sk.channel()).socket());
                System.out.println("spend:" + (e - b) + "ms");

            }
        }
    }
}