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
posted @   陶朱公Boy  阅读(101)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示