Java NIO- Selector 使用示例

Posted 夜行过客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java NIO- Selector 使用示例相关的知识,希望对你有一定的参考价值。

Selector selector = Selector.open();
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
while(true) {
  int readyChannels = selector.select();
  if(readyChannels == 0) continue;
  Set selectedKeys = selector.selectedKeys();
  Iterator 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();
  }
}

 

以上是关于Java NIO- Selector 使用示例的主要内容,如果未能解决你的问题,请参考以下文章

Netty——NIO(Selector处理read事件)代码示例

Netty——网络编程 NIO(Selector处理read事件)代码示例

Java NIO Selector

Java NIO系列教程 Selector

Netty——NIO(Selector处理accept事件)代码示例

Netty——NIO(Selector处理accept事件)代码示例