理解Buffer的limit和capacity這兩個值之間的區別是十分重要的。Capacity是某個Buffer對象所能包含的項數的最大值。Limit是在0到capacity之間的一個值,它表示一個限度,可以使用limit或者flip方法來設置它。我們來看下面的例子: // Sample of using flip buffer.position(5); buffer.flip(); while (buffer.hasRemaining()) { int i = buffer.get(); System.out.println("i="+i); }
另一個重要的Buffer類的方法是clear,它將設置position為0并設置limit為Buffer的容量值?;旧?,clear方法消除這之前flip(或limit)方法產生的影響??紤]下例: // Sample of using clear buffer.clear(); while (buffer.hasRemaining()) { int i = buffer.get(); System.out.println("i="+i); }
服務器端非阻塞(Server Nonblocking) 我以前的部分介紹過的實體都有與其相當的Java實體??蛻舳撕头掌鞫耸莾蓚€Java應用程序。套接字通道是SocketChannel類的實例,這個類答應通過網絡傳送數據。它們能被Java程序員看作是一個新的套接字。SocketChannel類被定義在java.nio.channel包中。 選擇器是一個Selector類的對象。該類的每個實例均能監視更多的套接字通道,進而建立更多的連接。當一些有意義的事發生在通道上(如客戶端試圖連接服務器端或進行讀/寫操作),選擇器便會通知應用程序處理請求。選擇器會創建一個要害字,這個要害字是SelectionKey類的一個實例。每個要害字都保存著應用程序的標識及請求的類型。其中,請求的類型可以是如下之一: ●嘗試連接(客戶端) ●嘗試連接(服務器端) ●讀取操作 ●寫入操作 一個通用的實現非阻塞服務器的算法如下: create SocketChannel; create Selector associate the SocketChannel to the Selector for(;;) { waiting events from the Selector; event arrived; create keys; for each key created by Selector { check the type of request; isAcceptable: get the client SocketChannel; associate that SocketChannel to the Selector; record it for read/write Operations continue; isReadable: get the client SocketChannel; read from the socket; continue; isWriteable: get the client SocketChannel; write on the socket; continue; } }