Posted on 2011-12-19 11:26
cooperzh 閱讀(264)
評論(0) 編輯 收藏 所屬分類:
NIO
channel 用于在 ByteBuffer 和socket(或文件)之間傳輸數據
channel的實現經常使用操作系統的本地代碼
implement InterruptibleChannel 后標示該通道可以被中斷,大多數channel都是可以被中斷的
面向字節的接口:ReadableByteChannel,WriteableByteChannel
ByteChannel接口繼承了ReadableByteChannel和WriteableByteChannel接口
IO廣義上可以分為file IO 和 stream IO,對應file通道和socket通道
file通道的類:FileChanel
socket通道的類:SocketChannel,ServerSocketChannel,DatagramChanenel
FileChannel不能直接創建,只能通過打開的RandomAccessFile,FileInputStream,FileOutputStream調用getChannel()獲得
socket通道可以直接調用其工廠方法獲得實例
只實現ReadableByteChannel或WriteableByteChannel的通道都是單向的,兩個都實現就是雙向的
實現ByteChannel的通道都是雙向的
所有socketChannel類都是雙向的
read() 將字節從通道讀入緩沖區
write() 將字節從緩沖區寫入通道
講byteBuffer的數據寫入通道:
while(buffer.hasRemaining()){
dest.write(buffer);
}
因為write操作可能會因為其他線程的調用而阻塞
緩沖區可以重復使用,而通道是一次性的,用完就關閉。通道關閉后,代表的與socket的連接會丟失
close方法是阻塞式的,多次close沒有壞處。close的實現取決于操作系統。
實現InterruptibleChannel接口的類,如果線程在該通道上被阻塞,同時線程被中斷,則通道將會關閉,阻塞線程會報異常:ClosedByInterruptException.
另外,設置了interrupt status的線訪問一個通道時,該通道將會立即被關閉,同時拋出ClosedByInterruptException異常
而線程的interrupt status是線程的interrupt()方法設置,并通過Thread.interrupted()清除。
通道上的線程休眠,則通道會關閉
當一個通道被關閉的時候,所有在此通道上休眠的線程都將被喚醒,并收到一個AsynchronousCloseException,接著通道被關閉。
一個通道同時對多個byteBuffer的操作稱為分散和聚合
Scatter分散體現在channel.read(ByteBuffer[] dsts) 和 channel.read(ByteBuffer[] dsts,int offset,int length);
Gather分散體現在channel.write(ByteBuffer[] dsts) 和 channel.write(ByteBuffer[] dsts,int offset,int length);
offset 和 length指的是ByteBuffer[]中第幾個ByteBuffer