1.什么是SelectionKey
A token representing the registration of a SelectableChannel with a Selector.
一個(gè)表示 SelectableChannel 向 Selector 注冊的令牌。
2.什么時(shí)候被創(chuàng)建
A selection key is created each time a channel is registered with a selector.
注冊到selector的時(shí)候被創(chuàng)建.
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. (
取消一個(gè)鍵并不會立即將其從其選擇器中移除;而是將其添加到選擇器的取消鍵集中,以便在下一次選擇操作期間刪除。)
5.兩個(gè)集合
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.幾個(gè)枚舉值
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);
//沒有連接的時(shí)候
if (!connected) {
//注冊connect事件.
selectionKey().interestOps(SelectionKey.OP_CONNECT);
}
success = true;
return connected;
} finally {
if (!success) {
doClose();
}
}
}
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);