JAVA NIO Selector Channel
- These four events are represented by the four
SelectionKey
constants:
- SelectionKey.OP_CONNECT
- SelectionKey.OP_ACCEPT
- SelectionKey.OP_READ
- 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 theChannel
, via theSelector
. There are four different events you can listen for:- Connect
- Accept
- Read
- 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?