channel與流的區別:java
channel的主要實現:服務器
- FileChannel
- DatagramChannel:UDP讀寫
- SocketChannel:TCP讀寫
- ServerSocketChannel
支持scatter/gather(分散和彙集)dom
ByteBuffer header = ByteBuffer.allocate(128); ByteBuffer body = ByteBuffer.allocate(1024); ByteBuffer[] bufferArray = { header, body }; channel.read(bufferArray);
通道的建立:異步
除了FileChannel以外,都使用open建立。socket
FileChannel的建立以下:spa
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();
Socket通道.net
分別對應java.net包中的Socket對象ServerSocket、Socket和DatagramSocket;Socket通道被實例化時,都會建立一個對等的Socket對象。code
Socket通道能夠運行非阻塞模式而且是可選擇的,非阻塞I/O與可選擇性是緊密相連的,這也正是管理阻塞的API要在 SelectableChannel中定義的緣由。設置非阻塞很是簡單,只要調用configureBlocking(false)方法便可。若是須要中 途更改阻塞模式,那麼必須首先得到blockingLock()方法返回的對象的鎖。對象
ServerSocketChannel實例:blog
1. 使用對等socket來bind監聽。
2. 非阻塞狀態下,accept在無鏈接時當即返回null
ByteBuffer buffer = ByteBuffer.wrap("Hello World".getBytes()); ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(12345)); ssc.configureBlocking(false); for (;;) { System.out.println("Waiting for connections"); SocketChannel sc = ssc.accept(); if (sc == null) TimeUnit.SECONDS.sleep(2000); else { System.out.println("Incoming connection from:" + sc.socket().getRemoteSocketAddress()); buffer.rewind(); sc.write(buffer); sc.close(); } }
非阻塞的read在無數據時當即返回0