2016-12-13 74 views
0

我正在使用NIO中的Java選擇器。我正在使用特定的頻道和選擇器註冊我的選擇鍵/興趣鍵。現在,我的要求是爲特定的選擇器設置兩個或多個興趣集。註冊多個SelectionKey

我所做的就是做兩個selectionkeys有不同的選擇選項如下:

try { 
     Selector selector = Selector.open(); 
     ServerSocketChannel channel = ServerSocketChannel.open(); 
     //FileChannel channel = new FileInputStream("").getChannel(); 

     channel.configureBlocking(false); 

     SelectionKey key1 = channel.register(selector, SelectionKey.OP_READ); 
     SelectionKey key2 = channel.register(selector, SelectionKey.OP_WRITE); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

我的問題是,有沒有什麼辦法可以避開做兩個不同勢鑰匙?

回答

0

可以二進制或鍵一起創建一個單一的興趣:

SelectionKey key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); 
+1

更常見的名稱是「按位或」 https://en.wikipedia.org/wiki/Bitwise_operation#OR –