1.什么是SelectionKey
A token representing the registration of a SelectableChannel with a Selector.
一个表示 SelectableChannel 向 Selector 注册的令牌。
2.什么时候被创建
A selection key is created each time a channel is registered with a selector.
注册到selector的时候被创建.
3.SelectionKey的生命周期
A key remains valid until it is cancelled by invoking its cancel method, by closing its channel, or by closing its selector.
4.取消
Cancelling a key does not immediately remove it from its selector; it is instead added to the selector's cancelled-key set for removal during the next selection operation. (
取消一个键并不会立即将其从其选择器中移除;而是将其添加到选择器的取消键集中,以便在下一次选择操作期间删除。)
5.两个集合
A selection key contains two operation sets represented as integer values. Each bit of an operation set denotes a category of selectable operations that are supported by the key's channel.
- The interest set
- The ready set
6.几个枚举值
public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;
7.netty中的使用.
NioSocketChannel里
//连接.
@Override
protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
if (localAddress != null) {
doBind0(localAddress);
}
boolean success = false;
try {
boolean connected = SocketUtils.connect(javaChannel(), remoteAddress);
//没有连接的时候
if (!connected) {
//注册connect事件.
selectionKey().interestOps(SelectionKey.OP_CONNECT);
}
success = true;
return connected;
} finally {
if (!success) {
doClose();
}
}
}
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);