javaNIO_之selector

Java NIO Selector//NIOselector详解can examine one or more NIO Channel's, and determine which channels are ready for e.g. reading or writing.
This way a single thread can manage multiple channels
Selector selector = Selector.open();//
channel.configureBlocking(false);

SelectionKey key = channel.register(selector, SelectionKey.OP_READ);//注册感兴趣的事件

四种感兴趣的事件,可以注册在通道上
    SelectionKey.OP_CONNECT
    SelectionKey.OP_ACCEPT
    SelectionKey.OP_READ
    SelectionKey.OP_WRITE

假如你对多个事件感兴趣的话,可以这样写
int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;    

SelectionKey's
在通道上注册感兴趣的选择器,调用register()将会返回SelectionKey对象,这个对象包含一系列感兴趣的属性
    The interest set
    The ready set
    The Channel
    The Selector
    An attached object (optional)
Interest Set:::::
int interestSet = selectionKey.interestOps();

boolean isInterestedInAccept  = interestSet & SelectionKey.OP_ACCEPT;
boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;
boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;
boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE;    
Ready Set:
selectionKey.isAcceptable();
selectionKey.isConnectable();
selectionKey.isReadable();
selectionKey.isWritable();
//作为测试events / operations the channel is ready for

Channel + Selector//使用SelectionKEY,将会返回通道和 selector

Channel  channel  = selectionKey.channel();

Selector selector = selectionKey.selector();

Attaching Objects:::::
 You can attach an object to a SelectionKey this is a handy way of recognizing a given channel,
 or attaching further information to the channel. For instance, you may attach the Buffer you are using with the channel,
 or an object containing more aggregate data. Here is how you attach objects:

selectionKey.attach(theObject);

Object attachedObj = selectionKey.attachment();

orSelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);




Selector selector = Selector.open();

channel.configureBlocking(false);

SelectionKey key = channel.register(selector, SelectionKey.OP_READ);


while(true) {

  int readyChannels = selector.select();//select将会阻塞,直到有一个或者多个相应的键准备好

  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.

    } else if (key.isConnectable()) {
        // a connection was established with a remote server.

    } else if (key.isReadable()) {
        // a channel is ready for reading

    } else if (key.isWritable()) {
        // a channel is ready for writing
    }

    keyIterator.remove();
  }
}

javaNIO_之selector_第1张图片

你可能感兴趣的:(javaNIO_之selector)