zoukankan      html  css  js  c++  java
  • JAVA NIO Selector Channel

    • These four events are represented by the four SelectionKey constants:
    1. SelectionKey.OP_CONNECT
    2. SelectionKey.OP_ACCEPT
    3. SelectionKey.OP_READ
    4. SelectionKey.OP_WRITE
    • Notice the second parameter of the register() method. This is an "interest set", meaning what events you are interested in listening for in the Channel, via the Selector. There are four different events you can listen for:

      1. Connect
      2. Accept
      3. Read
      4. Write
    • SelectionKey

    As you saw in the previous section, when you register a Channel with a Selector the register() method returns a SelectionKey objects. This SelectionKey object contains a few interesting properties:

    (如上一节中所见,当使用Selector注册Channel时,register()方法将返回SelectionKey对象。这个SelectionKey对象包含一些有趣的属性)

    • The interest set
    • The ready set
    • The Channel
    • The Selector
    • An attached object (optional)

    Here is a full example which opens a Selector, registers a channel with it (the channel instantiation is left out), and keeps monitoring the Selector for "readiness" of the four events (accept, connect, read, write).

    这是一个完整的示例,该示例打开一个选择器,向其注册一个通道(忽略通道实例化),并继续监视选择器以了解四个事件(接受,连接,读取,写入)的“就绪”状态


    Selector selector = Selector.open(); channel.configureBlocking(false); SelectionKey key = channel.register(selector, SelectionKey.OP_READ); while(true) { int readyChannels = selector.selectNow(); if(readyChannels == 0) continue; Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while(keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if(key.isAcceptable()) { // a connection was accepted by a ServerSocketChannel.(ServerSocketChannel接受了连接) } else if (key.isConnectable()) { // a connection was established with a remote server(与远程服务器建立连接). } else if (key.isReadable()) { // a channel is ready for reading(channel已准备就绪,可以阅读) } else if (key.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } }

     选择器完成后,将调用其close()方法。这将关闭选择器,并使在此选择器中注册的所有SelectionKey实例无效。通道本身未关闭


    参考链接
    http://tutorials.jenkov.com/java-nio/selectors.html
  • 相关阅读:
    闪回flashback
    Oracle数据文件在open状态被删除的恢复记录
    从浅到深掌握Oracle的锁
    Oracle 11g 11201_RHEL5.5_RAC_VBOX 详细搭建步骤
    AWR Report 关键参数详细分析
    16、Xtrabackup备份与恢复
    17、percona-toolkit
    插入排序
    选择排序
    冒泡排序
  • 原文地址:https://www.cnblogs.com/zhangfengshi/p/14010084.html
Copyright © 2011-2022 走看看