NIO下_使用樣本,NIO_使用樣本
一.分散與聚集
1.分散讀取(Scattering Reads):將通道中的資料分散到多個緩衝區中
2.聚集寫入(Gathering Writes):將多個緩衝區中的資料聚集到通道中
public void test4() throws IOException{
RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
//1. 擷取通道
FileChannel channel1 = raf1.getChannel();
//2. 分配指定大小的緩衝區
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
//3. 分散讀取
ByteBuffer[] bufs = {buf1, buf2};
channel1.read(bufs);
//4. 聚集寫入
RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
FileChannel channel2 = raf2.getChannel();
channel2.write(bufs);
}
二.字元集Charset
public void test6() throws IOException{Charset cs1 = Charset.forName("GBK");//擷取編碼器CharsetEncoder ce = cs1.newEncoder();//擷取解碼器CharsetDecoder cd = cs1.newDecoder();CharBuffer cBuf = CharBuffer.allocate(1024);cBuf.put("字元集!");cBuf.flip();//編碼ByteBuffer bBuf = ce.encode(cBuf);for (int i = 0; i < 12; i++) {System.out.println(bBuf.get());}//解碼bBuf.flip();CharBuffer cBuf2 = cd.decode(bBuf);System.out.println(cBuf2.toString());System.out.println("------------------------------------------------------");Charset cs2 = Charset.forName("UTF-8");bBuf.flip();CharBuffer cBuf3 = cs2.decode(bBuf);System.out.println(cBuf3.toString());}
三.NIO的非阻塞式(核心:Selector)
Selector(選取器)是Java NIO中能夠檢測一到多個NIO通道,並能夠知曉通道是否為諸如讀寫事件做好準備的組件。這樣,一個單獨的線程可以管理多個channel,從而管理多個網路連接.
1.TCP
eg:用戶端與服務端
//用戶端@Testpublic void client() throws IOException{//1. 擷取通道SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));//2. 切換非阻塞模式sChannel.configureBlocking(false);//3. 分配指定大小的緩衝區ByteBuffer buf = ByteBuffer.allocate(1024);//4. 發送資料給服務端Scanner scan = new Scanner(System.in);while(scan.hasNext()){String str = scan.next();buf.put((new Date().toString() + "\n" + str).getBytes());buf.flip();sChannel.write(buf);buf.clear();}//5. 關閉通道sChannel.close();}//服務端@Testpublic void server() throws IOException{//1. 擷取通道ServerSocketChannel ssChannel = ServerSocketChannel.open();//2. 切換非阻塞模式ssChannel.configureBlocking(false);//3. 綁定串連ssChannel.bind(new InetSocketAddress(9898));//4. 擷取選取器Selector selector = Selector.open();//5. 將通道註冊到選取器上, 並且指定“監聽接收事件”ssChannel.register(selector, SelectionKey.OP_ACCEPT);//6. 輪詢式的擷取選取器上已經“準備就緒”的事件while(selector.select() > 0){//7. 擷取當前選取器中所有註冊的“選擇鍵(已就緒的監聽事件)”Iterator<SelectionKey> it = selector.selectedKeys().iterator();while(it.hasNext()){//8. 擷取準備“就緒”的是事件SelectionKey sk = it.next();//9. 判斷具體是什麼事件準備就緒if(sk.isAcceptable()){//10. 若“接收就緒”,擷取用戶端串連SocketChannel sChannel = ssChannel.accept();//11. 切換非阻塞模式sChannel.configureBlocking(false);//12. 將該通道註冊到選取器上sChannel.register(selector, SelectionKey.OP_READ);}else if(sk.isReadable()){//13. 擷取當前選取器上“讀就緒”狀態的通道SocketChannel sChannel = (SocketChannel) sk.channel();//14. 讀取資料ByteBuffer buf = ByteBuffer.allocate(1024);int len = 0;while((len = sChannel.read(buf)) > 0 ){buf.flip();System.out.println(new String(buf.array(), 0, len));buf.clear();}}//15. 取消選擇鍵 SelectionKeyit.remove();}}}
2.UDP DatagramChannel
public void send() throws IOException{DatagramChannel dc = DatagramChannel.open();dc.configureBlocking(false);ByteBuffer buf = ByteBuffer.allocate(1024);Scanner scan = new Scanner(System.in);while(scan.hasNext()){String str = scan.next();buf.put((new Date().toString() + ":\n" + str).getBytes());buf.flip();dc.send(buf, new InetSocketAddress("127.0.0.1", 9898));buf.clear();}dc.close();}@Testpublic void receive() throws IOException{DatagramChannel dc = DatagramChannel.open();dc.configureBlocking(false);dc.bind(new InetSocketAddress(9898));Selector selector = Selector.open();dc.register(selector, SelectionKey.OP_READ);while(selector.select() > 0){Iterator<SelectionKey> it = selector.selectedKeys().iterator();while(it.hasNext()){SelectionKey sk = it.next();if(sk.isReadable()){ByteBuffer buf = ByteBuffer.allocate(1024);dc.receive(buf);buf.flip();System.out.println(new String(buf.array(), 0, buf.limit()));buf.clear();}}it.remove();}}
四.PIpe管道
Java NIO管道是2個線程之間的單向資料連線。pipe有一個source管道和一個sink管道。資料會被寫到sink通道,從source通道讀取
public void test1() throws IOException{//1. 擷取管道Pipe pipe = Pipe.open();//2. 將緩衝區中的資料寫入管道ByteBuffer buf = ByteBuffer.allocate(1024);Pipe.SinkChannel sinkChannel = pipe.sink();buf.put("通過單向管道發送資料".getBytes());buf.flip();sinkChannel.write(buf);//3. 讀取緩衝區中的資料Pipe.SourceChannel sourceChannel = pipe.source();buf.flip();int len = sourceChannel.read(buf);System.out.println(new String(buf.array(), 0, len));sourceChannel.close();sinkChannel.close();}