1. 程式人生 > >NIO阻塞與非阻塞式

NIO阻塞與非阻塞式

NIO的非阻塞模式

NIO完成核心的東西是一個選擇器,Selector,選擇器主要是將每一個傳輸資料的通道註冊到選擇器上,選擇器作用是監控這些IO的狀態(讀,寫,連線狀態),然後用選擇器監控通道的狀況,等待所有的執行緒準備就緒時,選擇器將任務分配到服務端一個或者多個執行緒上再去執行

NIO完成網路通訊的三個核心

1.通道(Channel):負責連線

java.nio.channels.Channel 介面:

​ SelectChannel介面下有,SocketChannel,ServerSocketChannel,DatagramChannel

​ pipe.SinkChannel和PipeSourceChannel

2.緩衝區(Buffer):負責資料的存取

3.選擇器(Selector):是SelectableChannel的多路複用器,用於監控SelectableChannel的IO狀況

阻塞式IO程式碼

package com.nio02;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.
ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class TestBlockingNIO { //客戶端 @Test public void client() throws IOException { //1. 獲取通道 SocketChannel sChannel = SocketChannel.open(new InetSocketAddress
("127.0.0.1", 9898)); FileChannel inChannel = FileChannel.open(Paths.get("a.txt"), StandardOpenOption.READ); //2. 分配指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //3. 讀取本地檔案,併發送到服務端 while (inChannel.read(buf) != -1) { buf.flip(); sChannel.write(buf); buf.clear(); } //4. 關閉通道 inChannel.close(); sChannel.close(); } //服務端 @Test public void server() throws IOException { //1. 獲取通道 ServerSocketChannel ssChannel = ServerSocketChannel.open(); FileChannel outChannel = FileChannel.open(Paths.get("a2.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); //2. 繫結連線 ssChannel.bind(new InetSocketAddress(9898)); //3. 獲取客戶端連線的通道 SocketChannel sChannel = ssChannel.accept(); //4. 分配指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //5. 接受客戶端的資料,並儲存到本地 while (sChannel.read(buf)!= -1){ buf.flip(); outChannel.write(buf); buf.clear(); } //6. 關閉通道 sChannel.close(); outChannel.close(); ssChannel.close(); } }

原本阻塞式IO需要shutdownOutput()

package com.nio02;

import org.junit.Test;
import scala.reflect.io.Path;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class TestBlockingNIO2 {
    //服務端
    @Test
    public void server() throws IOException {
        ServerSocketChannel ssChannel = ServerSocketChannel.open();

        FileChannel outChannel = FileChannel.open(Paths.get("a.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        ssChannel.bind(new InetSocketAddress(9898));

        SocketChannel sChannel = ssChannel.accept();

        ByteBuffer buf = ByteBuffer.allocate(1024);

        while (sChannel.read(buf)!= -1){
            buf.flip();
            outChannel.write(buf);
            buf.clear();
        }

        //傳送反饋給客戶端
        buf.put("服務端接受資料成功!".getBytes());
        buf.flip();
        sChannel.write(buf);

        sChannel.close();
        outChannel.close();
        ssChannel.close();
    }

    //客戶端
    @Test
    public void client() throws IOException {
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

        FileChannel inChannel = FileChannel.open(Paths.get("a.txt"),StandardOpenOption.READ);

        ByteBuffer buf = ByteBuffer.allocate(1024);

        while (inChannel.read(buf) != -1){
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }
        sChannel.shutdownOutput();
        //接受服務端的反饋
        int len = 0;
        while ((len = sChannel.read(buf))!= -1){
            buf.flip();
            System.out.println(new String(buf.array(),0,len));
            buf.clear();
        }
        inChannel.close();
        sChannel.close();
    }

}

非阻塞式IO操作

//客戶端
@Test
public 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();
}

//服務端
@Test
public 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. 取消選擇鍵 SelectionKey
			it.remove();
		}
	}
}