SelectionKey

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);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容