JAVA nio selector 入門

Selector(選擇器)是Java NIO中可以檢測一到多個NIO通道,並可以知曉通道是否爲諸如讀寫事件作好準備的組件。這樣,一個單獨的線程能夠管理多個channel,從而管理多個網絡鏈接java

 

爲何使用Selector?服務器

 

僅用單個線程來處理多個Channels的好處是,只須要更少的線程來處理通道。事實上,能夠只用一個線程處理全部的通道。對於操做系統來講,線程之間上下文切換的開銷很大,並且每一個線程都要佔用系統的一些資源(如內存)。所以,使用的線程越少越好。網絡

 

可是,須要記住,現代的操做系統和CPU在多任務方面表現的愈來愈好,因此多線程的開銷隨着時間的推移,變得愈來愈小了。實際上,若是一個CPU有多個內核,不使用多任務多是在浪費CPU能力。無論怎麼說,關於那種設計的討論應該放在另外一篇不一樣的文章中。在這裏,只要知道使用Selector可以處理多個通道就足夠了。多線程

 

Selector的建立socket

經過調用Selector.open()方法建立一個Selector,以下:編碼

Java代碼  收藏代碼spa

  1. Selector selector = Selector.open();  操作系統

 

向Selector註冊通道.net

爲了將Channel和Selector配合使用,必須將channel註冊到selector上。經過SelectableChannel.register()方法來實現,以下:線程

 

Java代碼  收藏代碼

  1. channel.configureBlocking(false);  

  2. SelectionKey key = channel.register(selector, Selectionkey.OP_READ);  

 

與Selector一塊兒使用時,Channel必須處於非阻塞模式下。這意味着不能將FileChannel與Selector一塊兒使用,由於FileChannel不能切換到非阻塞模式。而套接字通道均可以。

 

注意register()方法的第二個參數。這是一個「interest集合」,意思是在經過Selector監聽Channel時對什麼事件感興趣。能夠監聽四種不一樣類型的事件:

Connect

Accept

Read

Write

 

通道觸發了一個事件意思是該事件已經就緒。因此,某個channel成功鏈接到另外一個服務器稱爲「鏈接就緒」。一個server socket channel準備好接收新進入的鏈接稱爲「接收就緒」。一個有數據可讀的通道能夠說是「讀就緒」。等待寫數據的通道能夠說是「寫就緒」。

這四種事件用SelectionKey的四個常量來表示:

Java代碼  收藏代碼

  1. SelectionKey.OP_CONNECT  

  2. SelectionKey.OP_ACCEPT  

  3. SelectionKey.OP_READ  

  4. SelectionKey.OP_WRITE  

 

若是你對不止一種事件感興趣,那麼能夠用「位或」操做符將常量鏈接起來,以下:

Java代碼  收藏代碼

  1. int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;  

 

當向Selector註冊Channel時,register()方法會返回一個SelectionKey對象。這個對象包含了一些你感興趣的屬性:

 

interest集合

ready集合

Channel

Selector

附加的對象(可選)

 

下面我會描述這些屬性。

 

interest集合

 

就像向Selector註冊通道一節中所描述的,interest集合是你所選擇的感興趣的事件集合。能夠經過SelectionKey讀寫interest集合,像這樣:

Java代碼  收藏代碼

  1. int interestSet = selectionKey.interestOps();  

  2. boolean isInterestedInAccept  = interestSet & SelectionKey.OP_ACCEPT;  

  3. boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;  

  4. boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;  

  5. boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE;   

 能夠看到,用「位與」操做interest 集合和給定的SelectionKey常量,能夠肯定某個肯定的事件是否在interest 集合中。

 

ready集合

 

ready 集合是通道已經準備就緒的操做的集合。在一次選擇(Selection)以後,你會首先訪問這個ready set。Selection將在下一小節進行解釋。能夠這樣訪問ready集合:

Java代碼  收藏代碼

  1. int readySet = selectionKey.readyOps();  

 

能夠用像檢測interest集合那樣的方法,來檢測channel中什麼事件或操做已經就緒。可是,也可使用如下四個方法,它們都會返回一個布爾類型:

Java代碼  收藏代碼

  1. selectionKey.isAcceptable();  

  2. selectionKey.isConnectable();  

  3. selectionKey.isReadable();  

  4. selectionKey.isWritable();  

 

Channel + Selector

 

從SelectionKey訪問Channel和Selector很簡單。以下:

 

Java代碼  收藏代碼

  1. Channel  channel  = selectionKey.channel();  

  2. Selector selector = selectionKey.selector();  

 

附加的對象

 

能夠將一個對象或者更多信息附着到SelectionKey上,這樣就能方便的識別某個給定的通道。例如,能夠附加 與通道一塊兒使用的Buffer,或是包含彙集數據的某個對象。使用方法以下:

Java代碼  收藏代碼

  1. selectionKey.attach(theObject);  

  2. Object attachedObj = selectionKey.attachment();  

 

還能夠在用register()方法向Selector註冊Channel的時候附加對象。如:

Java代碼  收藏代碼

  1. SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);  

 

經過Selector選擇通道

 

一旦向Selector註冊了一或多個通道,就能夠調用幾個重載的select()方法。這些方法返回你所感興趣的事件(如鏈接、接受、讀或寫)已經準備就緒的那些通道。換句話說,若是你對「讀就緒」的通道感興趣,select()方法會返回讀事件已經就緒的那些通道。

 

下面是select()方法:(該方法是阻塞方法

 

int select()

int select(long timeout)

int selectNow()

select()阻塞到至少有一個通道在你註冊的事件上就緒了。

 

select(long timeout)和select()同樣,除了最長會阻塞timeout毫秒(參數)。

 

selectNow()不會阻塞,無論什麼通道就緒都馬上返回(譯者注:此方法執行非阻塞的選擇操做。若是自從前一次選擇操做後,沒有通道變成可選擇的,則此方法直接返回零。)。

 

select()方法返回的int值表示有多少通道已經就緒。亦即,自上次調用select()方法後有多少通道變成就緒狀態。若是調用select()方法,由於有一個通道變成就緒狀態,返回了1,若再次調用select()方法,若是另外一個通道就緒了,它會再次返回1。若是對第一個就緒的channel沒有作任何操做,如今就有兩個就緒的通道,但在每次select()方法調用之間,只有一個通道就緒了。

 

selectedKeys()

 

一旦調用了select()方法,而且返回值代表有一個或更多個通道就緒了,而後能夠經過調用selector的selectedKeys()方法,訪問「已選擇鍵集(selected key set)」中的就緒通道。以下所示:

Java代碼  收藏代碼

  1. Set selectedKeys = selector.selectedKeys();  

 

當像Selector註冊Channel時,Channel.register()方法會返回一個SelectionKey 對象。這個對象表明了註冊到該Selector的通道。能夠經過SelectionKey的selectedKeySet()方法訪問這些對象。

能夠遍歷這個已選擇的鍵集合來訪問就緒的通道。以下:

Java代碼  收藏代碼

  1. Set selectedKeys = selector.selectedKeys();  

  2. Iterator keyIterator = selectedKeys.iterator();  

  3. while(keyIterator.hasNext()) {  

  4.     SelectionKey key = keyIterator.next();  

  5.     if(key.isAcceptable()) {  

  6.         // a connection was accepted by a ServerSocketChannel.  

  7.     } else if (key.isConnectable()) {  

  8.         // a connection was established with a remote server.  

  9.     } else if (key.isReadable()) {  

  10.         // a channel is ready for reading  

  11.     } else if (key.isWritable()) {  

  12.         // a channel is ready for writing  

  13.     }  

  14.     keyIterator.remove();  

  15. }  

 

這個循環遍歷已選擇鍵集中的每一個鍵,並檢測各個鍵所對應的通道的就緒事件。

 

注意每次迭代末尾的keyIterator.remove()調用。Selector不會本身從已選擇鍵集中移除SelectionKey實例。必須在處理完通道時本身移除。下次該通道變成就緒時,Selector會再次將其放入已選擇鍵集中

 

SelectionKey.channel()方法返回的通道須要轉型成你要處理的類型,如ServerSocketChannel或SocketChannel等。

 

wakeUp()

 

某個線程調用select()方法後阻塞了,即便沒有通道已經就緒,也有辦法讓其從select()方法返回。只要讓其它線程在第一個線程調用select()方法的那個對象上調用Selector.wakeup()方法便可。阻塞在select()方法上的線程會立馬返回。

 

若是有其它線程調用了wakeup()方法,但當前沒有線程阻塞在select()方法上,下個調用select()方法的線程會當即「醒來(wake up)」。

 

close()

 

用完Selector後調用其close()方法會關閉該Selector,且使註冊到該Selector上的全部SelectionKey實例無效。通道自己並不會關閉。

 

 

----------------------------------------------------------------------------------------------------

下面的例子是當客戶端發送的字符串,server端接收並打印,而後將接收的字符串反饋給client

 

server端代碼

Java代碼  收藏代碼

  1. package hb.server;  

  2.   

  3. import java.io.*;  

  4. import java.nio.*;  

  5. import java.nio.channels.*;  

  6. import java.nio.channels.spi.*;  

  7. import java.net.*;  

  8. import java.util.*;  

  9. import java.nio.charset.*;  

  10.   

  11. public class NServer {  

  12.     // 用於檢測全部Channel狀態的Selector  

  13.     private Selector selector = null;  

  14.     // 定義實現編碼、解碼的字符集對象  

  15.     private Charset charset = Charset.forName("UTF-8");  

  16.   

  17.     public void init() throws IOException {  

  18.         selector = Selector.open();  

  19.         // 經過open方法來打開一個未綁定的ServerSocketChannel實例  

  20.         ServerSocketChannel server = ServerSocketChannel.open();  

  21.         InetSocketAddress isa = new InetSocketAddress("127.0.0.1"30000);  

  22.         // 將該ServerSocketChannel綁定到指定IP地址  

  23.         server.socket().bind(isa);  

  24.         // 設置ServerSocket以非阻塞方式工做  

  25.         server.configureBlocking(false);  

  26.         // 將server註冊到指定Selector對象  

  27.         server.register(selector, SelectionKey.OP_ACCEPT);  

  28.         while (selector.select() > 0) {  

  29.             // 依次處理selector上的每一個已選擇的SelectionKey  

  30.             for (SelectionKey sk : selector.selectedKeys()) {  

  31.                 // 從selector上的已選擇Key集中刪除正在處理的SelectionKey  

  32.                 selector.selectedKeys().remove(sk);  

  33.                 // 若是sk對應的通道包含客戶端的鏈接請求  

  34.                 if (sk.isAcceptable()) {  

  35.                     // 調用accept方法接受鏈接,產生服務器端對應的SocketChannel  

  36.                     SocketChannel sc = server.accept();  

  37.                     // 設置採用非阻塞模式  

  38.                     sc.configureBlocking(false);  

  39.                     // 將該SocketChannel也註冊到selector  

  40.                     sc.register(selector, SelectionKey.OP_READ);  

  41.                     // 將sk對應的Channel設置成準備接受其餘請求  

  42.                     sk.interestOps(SelectionKey.OP_ACCEPT);  

  43.                 }  

  44.                 // 若是sk對應的通道有數據須要讀取  

  45.                 if (sk.isReadable()) {  

  46.                     // 獲取該SelectionKey對應的Channel,該Channel中有可讀的數據  

  47.                     SocketChannel sc = (SocketChannel) sk.channel();  

  48.                     // 定義準備執行讀取數據的ByteBuffer  

  49.                     ByteBuffer buff = ByteBuffer.allocate(1024);  

  50.                     String content = "";  

  51.                     // 開始讀取數據  

  52.                     try {  

  53.                         while (sc.read(buff) > 0) {  

  54.                             buff.flip();  

  55.                             content += charset.decode(buff);  

  56.                         }  

  57.                         // 打印從該sk對應的Channel裏讀取到的數據  

  58.                         System.out.println("=====" + content);  

  59.                         // 將sk對應的Channel設置成準備下一次讀取  

  60.                         sk.interestOps(SelectionKey.OP_READ);  

  61.                     }  

  62.                     // 若是捕捉到該sk對應的Channel出現了異常,即代表該Channel  

  63.                     // 對應的Client出現了問題,因此從Selector中取消sk的註冊  

  64.                     catch (IOException ex) {  

  65.                         // 從Selector中刪除指定的SelectionKey  

  66.                         sk.cancel();  

  67.                         if (sk.channel() != null) {  

  68.                             sk.channel().close();  

  69.                         }  

  70.                     }  

  71.                     // 若是content的長度大於0,即聊天信息不爲空  

  72.                     if (content.length() > 0) {  

  73.                         // 遍歷該selector裏註冊的全部SelectKey  

  74.                         for (SelectionKey key : selector.keys()) {  

  75.                             // 獲取該key對應的Channel  

  76.                             Channel targetChannel = key.channel();  

  77.                             // 若是該channel是SocketChannel對象  

  78.                             if (targetChannel instanceof SocketChannel) {  

  79.                                 // 將讀到的內容寫入該Channel中  

  80.                                 SocketChannel dest = (SocketChannel) targetChannel;  

  81.                                 dest.write(charset.encode(content));  

  82.                             }  

  83.                         }  

  84.                     }  

  85.                 }  

  86.             }  

  87.         }  

  88.     }  

  89.   

  90.     public static void main(String[] args) throws IOException {  

  91.         new NServer().init();  

  92.     }  

  93. }  

 

客戶端

Java代碼  收藏代碼

  1. package hb.server;  

  2.   

  3. import java.io.*;  

  4. import java.net.*;  

  5. import java.nio.*;  

  6. import java.nio.channels.*;  

  7. import java.nio.charset.*;  

  8. import java.util.*;  

  9.   

  10. public class NClient  

  11. {  

  12.     //定義檢測SocketChannel的Selector對象  

  13.     private Selector selector = null;  

  14.     //定義處理編碼和解碼的字符集  

  15.     private Charset charset = Charset.forName("UTF-8");  

  16.     //客戶端SocketChannel  

  17.     private SocketChannel sc = null;  

  18.     public void init()throws IOException  

  19.     {  

  20.         selector = Selector.open();  

  21.         InetSocketAddress isa = new InetSocketAddress("127.0.0.1"30000);  

  22.         //調用open靜態方法建立鏈接到指定主機的SocketChannel  

  23.         sc = SocketChannel.open(isa);  

  24.         //設置該sc以非阻塞方式工做  

  25.         sc.configureBlocking(false);  

  26.         //將SocketChannel對象註冊到指定Selector  

  27.         sc.register(selector, SelectionKey.OP_READ);  

  28.         //啓動讀取服務器端數據的線程  

  29.         new ClientThread().start();  

  30.         //建立鍵盤輸入流  

  31.         Scanner scan = new Scanner(System.in);  

  32.         while (scan.hasNextLine())  

  33.         {  

  34.             //讀取鍵盤輸入  

  35.             String line = scan.nextLine();  

  36.             //將鍵盤輸入的內容輸出到SocketChannel中  

  37.             sc.write(charset.encode(line));  

  38.         }  

  39.     }  

  40.     //定義讀取服務器數據的線程  

  41.     private class ClientThread extends Thread  

  42.     {  

  43.         public void run()  

  44.         {  

  45.             try  

  46.             {  

  47.                 while (selector.select() > 0)   

  48.                 {  

  49.                     //遍歷每一個有可用IO操做Channel對應的SelectionKey  

  50.                     for (SelectionKey sk : selector.selectedKeys())  

  51.                     {  

  52.                         //刪除正在處理的SelectionKey  

  53.                         selector.selectedKeys().remove(sk);  

  54.                         //若是該SelectionKey對應的Channel中有可讀的數據  

  55.                         if (sk.isReadable())  

  56.                         {  

  57.                             //使用NIO讀取Channel中的數據  

  58.                             SocketChannel sc = (SocketChannel)sk.channel();  

  59.                             ByteBuffer buff = ByteBuffer.allocate(1024);  

  60.                             String content = "";  

  61.                             while(sc.read(buff) > 0)  

  62.                             {  

  63.                                 sc.read(buff);   

  64.                                 buff.flip();  

  65.                                 content += charset.decode(buff);  

  66.                             }  

  67.                             //打印輸出讀取的內容  

  68.                             System.out.println("聊天信息:" + content);  

  69.                             //爲下一次讀取做準備  

  70.                             sk.interestOps(SelectionKey.OP_READ);  

  71.                         }  

  72.                     }  

  73.                 }  

  74.             }  

  75.             catch (IOException ex)  

  76.             {  

  77.                 ex.printStackTrace();  

  78.             }  

  79.         }  

  80.     }  

  81.   

  82.     public static void main(String[] args)  

  83.         throws IOException  

  84.     {  

  85.         new NClient().init();  

  86.     }  

  87. }  

相關文章
相關標籤/搜索