JAVA nio selector 入門
Selector(選擇器)是Java NIO中能夠檢測一到多個NIO通道,并能夠知曉通道是否為諸如讀寫事件做好準備的組件。這樣,一個單獨的線程可以管理多個channel,從而管理多個網絡連接。
為什么使用Selector?
僅用單個線程來處理多個Channels的好處是,只需要更少的線程來處理通道。事實上,可以只用一個線程處理所有的通道。對于操作系統來說,線程之間上下文切換的開銷很大,而且每個線程都要占用系統的一些資源(如內存)。因此,使用的線程越少越好。
但是,需要記住,現代的操作系統和CPU在多任務方面表現的越來越好,所以多線程的開銷隨著時間的推移,變得越來越小了。實際上,如果一個CPU有多個內核,不使用多任務可能是在浪費CPU能力。不管怎么說,關于那種設計的討論應該放在另一篇不同的文章中。在這里,只要知道使用Selector能夠處理多個通道就足夠了。
Selector的創建
通過調用Selector.open()方法創建一個Selector,如下:
Selector selector = Selector.open();
向Selector注冊通道
為了將Channel和Selector配合使用,必須將channel注冊到selector上。通過SelectableChannel.register()方法來實現,如下:
channel.configureBlocking(false);
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的四個常量來表示:
SelectionKey.OP_CONNECT
SelectionKey.OP_ACCEPT
SelectionKey.OP_READ
SelectionKey.OP_WRITE
如果你對不止一種事件感興趣,那么可以用“位或”操作符將常量連接起來,如下:
int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
當向Selector注冊Channel時,register()方法會返回一個SelectionKey對象。這個對象包含了一些你感興趣的屬性:
interest集合
ready集合
Channel
Selector
附加的對象(可選)
下面我會描述這些屬性。
interest集合
就像向Selector注冊通道一節中所描述的,interest集合是你所選擇的感興趣的事件集合。可以通過SelectionKey讀寫interest集合,像這樣:
int interestSet = selectionKey.interestOps();
boolean isInterestedInAccept = interestSet & SelectionKey.OP_ACCEPT;
boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;
boolean isInterestedInRead = interestSet & SelectionKey.OP_READ;
boolean isInterestedInWrite = interestSet & SelectionKey.OP_WRITE;
可以看到,用“位與”操作interest 集合和給定的SelectionKey常量,可以確定某個確定的事件是否在interest 集合中。
ready集合
ready 集合是通道已經準備就緒的操作的集合。在一次選擇(Selection)之后,你會首先訪問這個ready set。Selection將在下一小節進行解釋。可以這樣訪問ready集合:
int readySet = selectionKey.readyOps();
可以用像檢測interest集合那樣的方法,來檢測channel中什么事件或操作已經就緒。但是,也可以使用以下四個方法,它們都會返回一個布爾類型:
selectionKey.isAcceptable();
selectionKey.isConnectable();
selectionKey.isReadable();
selectionKey.isWritable();
Channel + Selector
從SelectionKey訪問Channel和Selector很簡單。如下:
Channel channel = selectionKey.channel();
Selector selector = selectionKey.selector();
附加的對象
可以將一個對象或者更多信息附著到SelectionKey上,這樣就能方便的識別某個給定的通道。例如,可以附加 與通道一起使用的Buffer,或是包含聚集數據的某個對象。使用方法如下:
selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment();
還可以在用register()方法向Selector注冊Channel的時候附加對象。如:
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)”中的就緒通道。如下所示:
Set selectedKeys = selector.selectedKeys();
當像Selector注冊Channel時,Channel.register()方法會返回一個SelectionKey 對象。這個對象代表了注冊到該Selector的通道。可以通過SelectionKey的selectedKeySet()方法訪問這些對象。
可以遍歷這個已選擇的鍵集合來訪問就緒的通道。如下:
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
}
keyIterator.remove();
}
這個循環遍歷已選擇鍵集中的每個鍵,并檢測各個鍵所對應的通道的就緒事件。
注意每次迭代末尾的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端代碼
package hb.server;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;
public class NServer {
// 用于檢測所有Channel狀態的Selector
private Selector selector = null;
// 定義實現編碼、解碼的字符集對象
private Charset charset = Charset.forName("UTF-8");
public void init() throws IOException {
selector = Selector.open();
// 通過open方法來打開一個未綁定的ServerSocketChannel實例
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 30000);
// 將該ServerSocketChannel綁定到指定IP地址
server.socket().bind(isa);
// 設置ServerSocket以非阻塞方式工作
server.configureBlocking(false);
// 將server注冊到指定Selector對象
server.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0) {
// 依次處理selector上的每個已選擇的SelectionKey
for (SelectionKey sk : selector.selectedKeys()) {
// 從selector上的已選擇Key集中刪除正在處理的SelectionKey
selector.selectedKeys().remove(sk);
// 如果sk對應的通道包含客戶端的連接請求
if (sk.isAcceptable()) {
// 調用accept方法接受連接,產生服務器端對應的SocketChannel
SocketChannel sc = server.accept();
// 設置采用非阻塞模式
sc.configureBlocking(false);
// 將該SocketChannel也注冊到selector
sc.register(selector, SelectionKey.OP_READ);
// 將sk對應的Channel設置成準備接受其他請求
sk.interestOps(SelectionKey.OP_ACCEPT);
}
// 如果sk對應的通道有數據需要讀取
if (sk.isReadable()) {
// 獲取該SelectionKey對應的Channel,該Channel中有可讀的數據
SocketChannel sc = (SocketChannel) sk.channel();
// 定義準備執行讀取數據的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
// 開始讀取數據
try {
while (sc.read(buff) > 0) {
buff.flip();
content += charset.decode(buff);
}
// 打印從該sk對應的Channel里讀取到的數據
System.out.println("=====" + content);
// 將sk對應的Channel設置成準備下一次讀取
sk.interestOps(SelectionKey.OP_READ);
}
// 如果捕捉到該sk對應的Channel出現了異常,即表明該Channel
// 對應的Client出現了問題,所以從Selector中取消sk的注冊
catch (IOException ex) {
// 從Selector中刪除指定的SelectionKey
sk.cancel();
if (sk.channel() != null) {
sk.channel().close();
}
}
// 如果content的長度大于0,即聊天信息不為空
if (content.length() > 0) {
// 遍歷該selector里注冊的所有SelectKey
for (SelectionKey key : selector.keys()) {
// 獲取該key對應的Channel
Channel targetChannel = key.channel();
// 如果該channel是SocketChannel對象
if (targetChannel instanceof SocketChannel) {
// 將讀到的內容寫入該Channel中
SocketChannel dest = (SocketChannel) targetChannel;
dest.write(charset.encode(content));
}
}
}
}
}
}
}
public static void main(String[] args) throws IOException {
new NServer().init();
}
}
客戶端
package hb.server;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
public class NClient
{
//定義檢測SocketChannel的Selector對象
private Selector selector = null;
//定義處理編碼和解碼的字符集
private Charset charset = Charset.forName("UTF-8");
//客戶端SocketChannel
private SocketChannel sc = null;
public void init()throws IOException
{
selector = Selector.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 30000);
//調用open靜態方法創建連接到指定主機的SocketChannel
sc = SocketChannel.open(isa);
//設置該sc以非阻塞方式工作
sc.configureBlocking(false);
//將SocketChannel對象注冊到指定Selector
sc.register(selector, SelectionKey.OP_READ);
//啟動讀取服務器端數據的線程
new ClientThread().start();
//創建鍵盤輸入流
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine())
{
//讀取鍵盤輸入
String line = scan.nextLine();
//將鍵盤輸入的內容輸出到SocketChannel中
sc.write(charset.encode(line));
}
}
//定義讀取服務器數據的線程
private class ClientThread extends Thread
{
public void run()
{
try
{
while (selector.select() > 0)
{
//遍歷每個有可用IO操作Channel對應的SelectionKey
for (SelectionKey sk : selector.selectedKeys())
{
//刪除正在處理的SelectionKey
selector.selectedKeys().remove(sk);
//如果該SelectionKey對應的Channel中有可讀的數據
if (sk.isReadable())
{
//使用NIO讀取Channel中的數據
SocketChannel sc = (SocketChannel)sk.channel();
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
while(sc.read(buff) > 0)
{
sc.read(buff);
buff.flip();
content += charset.decode(buff);
}
//打印輸出讀取的內容
System.out.println("聊天信息:" + content);
//為下一次讀取作準備
sk.interestOps(SelectionKey.OP_READ);
}
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
public static void main(String[] args)
throws IOException
{
new NClient().init();
}
}