- 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