標籤:code master col 多個 href 定義 this trace 封裝
- 通道
- 通道基礎
- Scatter/Gather
- 檔案通道
- Socket通道
- 總結
通道
channel用於位元組緩衝區和位於通道另一側的實體(通常是一個檔案或通訊端)之間有效傳輸資料。
通道時一種途徑,通過這種途徑,可以用最小的總開銷來訪問作業系統本身的IO服務,緩衝區則是通道內部用於發送和接受資料的斷點。
通道基礎
頂層介面Channel,次級介面WritableByteChannel、ReadableByteChannel、InterruptibleChannel等。描述通道行為的介面在java.nio.channels包中定義,具體的通道實現都是從java.nio.channels.spi中的類引申來的。
通道開啟
IO可以分為廣義的兩大類:File IO和Stream IO,對應File通道和Socket通道。體現在FileChannel類和三個socket通道類:SocketChannel、ServerSocketChannel和DatagramChannel。
代碼如下:
//開啟SocketChannel SocketChannel sc = SocketChannel.open( ); sc.connect (new InetSocketAddress("somehost", port)); //開啟ServerSocketChannel ServerSocketChannel ssc = ServerSocketChannel.open( ); ssc.socket( ).bind (new InetSocketAddress (port)); DatagramChannel dc = DatagramChannel.open( ); //FileChannel只能通過 RandomAccessFile、FileInputStream 或 FileOutputStream 對象上調用 getChannel( )方法來擷取 RandomAccessFile raf = new RandomAccessFile ("somefile", "r"); FileChannel fc = raf.getChannel( );
通道使用
利用通道,從控制台接收輸入,並在控制台列印出接收的輸入。代碼如下:
public static void main(String[] args) throws IOException { //一個讀通道,一個寫通道 ReadableByteChannel source = Channels.newChannel(System.in); WritableByteChannel dest = Channels.newChannel(System.out); channelCopy(source,dest); source.close(); dest.close(); } private static void channelCopy(ReadableByteChannel source, WritableByteChannel dest) throws IOException{ ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 1024); ByteBuffer flag = ByteBuffer.allocate(4); while (source.read(byteBuffer) != -1) { byteBuffer.flip(); //輸出標記 flag.put((byte)‘-‘).put((byte)‘-‘).put((byte)‘-‘).put((byte) ‘>‘); flag.flip(); dest.write(flag); dest.write(byteBuffer); flag.clear(); byteBuffer.compact(); } byteBuffer.flip(); //確保緩衝區排乾淨 while (byteBuffer.hasRemaining()) { flag.putChar(‘-‘).putChar(‘-‘).putChar(‘-‘); flag.flip(); dest.write(byteBuffer); flag.clear(); } }
測試輸入輸出如下:
通道關閉
與緩衝區不同,通道不能重複利用,開啟通道即代表與一個特定的IO服務的特定連結並封裝該連結的狀態,通道關閉時,串連丟失,通道不在串連任何東西。
調用close方法時,可能導致線程暫時阻塞,關閉的通道上調用close方法不會產生任何操作,只會立即返回。可以通過isOpen方法判斷通道狀態。
如果一個線程被中斷,那麼這個線程訪問的通道將立即關閉,這也是為程式健壯性而採用的一種權衡。
Scatter/Gather
在多個緩衝區實現一個簡單的IO操作:
對於write,資料是從幾個緩衝區按順序抽取(gather)並沿著通道發送。該gather過程,好比全部緩衝區內容被串連起來,並在發送前存放到一個大的緩衝區。
對於read,從通道讀取的資料會被按順序散布(scatter)到多個緩衝區,將每個緩衝區填滿直至通道中的資料或緩衝區的空間被消耗完。
介面定義如下, 其中read和write入參時Buffer數組:
public interface ScatteringByteChannel extends ReadableByteChannel{ public long read (ByteBuffer [] dsts) throws IOException; public long read (ByteBuffer [] dsts, int offset, int length) throws IOException;}public interface GatheringByteChannel extends WritableByteChannel{ public long write(ByteBuffer[] srcs) throws IOException; public long write(ByteBuffer[] srcs, int offset, int length) throws IOException;}
檔案通道
具體來講FileChannel,介面如下:
public abstract class FileChannel extends AbstractInterruptibleChannel implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel
FileChannel 對象是安全執行緒(thread-safe)的.
對於檔案IO,最強大之處在於非同步IO,它允許一個進程可以從作業系統請求一個或多個IO操作而不必等待這些操作完成。
檔案通道程式碼範例
public static void write(String filePath) throws Exception { /*寫檔案,使用FileOutputStream,RandomAccessFile都可以。*//* RandomAccessFile file = new RandomAccessFile(filePath,"rw");*/ FileOutputStream file = new FileOutputStream(new File(filePath)); ByteBuffer byteBuffer = ByteBuffer.allocate(500); String str = "hello LK"; /*資料寫入緩衝區*/ byteBuffer.put(str.getBytes()); byteBuffer.flip(); FileChannel fileChannel = file.getChannel(); //將緩衝區資料寫入檔案通道 fileChannel.write(byteBuffer); byteBuffer.clear(); fileChannel.close(); }
public static void read(String filePath) throws Exception { FileInputStream fileInputStream = new FileInputStream(new File(filePath)); /*一個FileChannel對象卻只能通過 在一個開啟的RandomAccessFile、FileInputStream或FileOutputStream對象上調用getChannel()方法來擷取, 開發人員不能直接建立一個FileChannel*/ FileChannel fileChannel = fileInputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(500); //將檔案channel讀入緩衝區 fileChannel.read(byteBuffer); byteBuffer.flip(); while (byteBuffer.hasRemaining()){ System.out.print((char)byteBuffer.get()); } byteBuffer.clear(); fileChannel.close(); }
Socket通道
新的Socket通道類可以運行非阻塞模式,並且是可選擇的。藉助新的NIO類,一個或幾個線程可以管理成百上千的活動socket串連,並且只有很少的效能順勢。
全部 socket 通道類(DatagramChannel、SocketChannel 和 ServerSocketChannel)都是由位於java.nio.channels.spi 包中的AbstractSelectableChannel引申而來。
DatagramChannel 和 SocketChannel 實現定義讀和寫功能的介面而 ServerSocketChannel 不實現。ServerSocketChannel 負責監聽傳入的串連和建立新的SocketChannel 對象,它本身從不傳 輸資料。
Socket通道程式碼範例
啟動一個ServerSocketChannel,監聽8001連接埠,非阻塞模式。啟動10個SocketChannel線程向ServerSocketChannel寫資料。
ServerSocketChannel代碼如下:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); /*非阻塞*/ serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress(port)); System.out.println("ServerSocketChannel is OK,waiting @[" + LocalDateTime.now() + "]"); for (; ; ) { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel == null) { Thread.sleep(1000); System.out.println("ServerSocketChannel sleep 1000ms."); continue; } String connectIP = socketChannel.socket().getRemoteSocketAddress().toString(); System.out.println("用戶端已有資料到來,用戶端ip為:" + connectIP + ", 時間為" + LocalDateTime.now()); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); socketChannel.read(byteBuffer); byteBuffer.flip(); while (byteBuffer.hasRemaining()) { System.out.print((char) byteBuffer.get()); } socketChannel.close(); } }
啟動10個SocketCHannel代碼如下:
private static final int port = 8001; public static void main(String[] args) { for (int i=0;i<10;i++) { new SocketChannelImpl(port,i).start(); } } private static class SocketChannelImpl extends Thread { private int count = 0; private int port; public SocketChannelImpl(int port,int count){ this.port = port; this.count = count; } @Override public void run() { try { SocketChannel socketChannel = SocketChannel.open(); /*非阻塞*/ socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(port)); for (;!socketChannel.finishConnect();) { System.out.println("connectting...."); Thread.sleep(50); } ByteBuffer byteBuffer = ByteBuffer.allocate(1024); String content = "hello, i am client--------->" + count; byteBuffer.put(content.getBytes()); byteBuffer.flip(); socketChannel.write(byteBuffer); byteBuffer.clear(); socketChannel.close(); } catch (Exception e) { e.printStackTrace(); } } }
運行結果如下:
補充下:
ServerSocketChannel監聽的是8001連接埠,你可以在瀏覽器,輸入:http://localhost:8001/helloworld,你會發現你的ServerSocketChannel也是可以收到資料了,這也web伺服器處理的基礎了。
總結
以上,瞭解了基本的通道操作,檔案通道和socket通道的使用樣本,我覺得點個贊,不過分=。=
以上所有程式碼範例,可以fork這裡:github
謝謝
以上來自天團運營總監:坤少
Java NIO之通道