想要徹底理解Netty,你需要先搞明白NIO

I/O模型

I/O模型簡單理解就是用什么樣的通道進行數據的發生和接收,這個很大程度上覺得了程序通信的性能。
Java有三種網絡編程模型,分別是BIO、NIO和NIO。

BIO
同步并阻塞,一個連接一個線程,即客戶端有請求服務端就會開啟一個線程進行處理。缺點就是如果這個連接不做任何事情就會造成不必要的線程開銷。


BIO示意圖

NIO
同步非阻塞,一個線程處理多個請求,客戶端請求會注冊到多路復用器上,多路復用器輪詢到連接有I/O請求就進行處理。


NIO示意圖

AIO
異步非阻塞IO,AIO引入異步通道的概念,采用了Proactor模式,簡化了程序編寫,有效的請求才啟動線程,它的特點是先由操作系統完成后才通知服務端程序啟動程序去處理,一般適合用于連接數較多且連接時間較長的應用。不常用,所以這里不做過多講解。

三種IO模型的應用場景

BIO適合于鏈接數目較少且固定的架構,這種方式對服務器的資源要求較高,JDK1.4之前的唯一選擇,程序簡單易理解。

NIO適合于連接數目較多且連接比較短的架構,比如聊天服務器、服務期間通信等,編程較復雜。JDK1.4新增。

AIO適用于連接數多且連接時間較長的架構。編程較復雜,JDK1.7開始支持。

BIO

Java BIO就是傳統的Java io編程,相關類和接口都在java.io包下。前面已經說過,它是同步阻塞的,一個連接就啟動一個線程,比較浪費服務器資源。

需求: 使用BIO實現一個服務器端,監聽10000端口,當客戶端連接時,就啟動一個線程與之通訊,要求使用線程池。

public class BioServer {

    public static void main(String[] args) throws Exception {
        //1.創建一個線程池
        ExecutorService pool = Executors.newCachedThreadPool();
        //2.如果有請求, 就創建一個線程與之通信
        //創建服務端
        ServerSocket serverSocket = new ServerSocket(10000);
        System.out.println("服務器啟動.");
        while (true){
            System.out.println("等待連接......");
            final Socket socket = serverSocket.accept();
            System.out.println("有新連接");
            //創建一個線程與之通信
            pool.execute(new Runnable() {
                public void run() {
                    handler(socket);
                }
            });
        }
    }

    /**
     * 處理客戶端請求
     * @param socket
     */
    public static void handler(Socket socket){
        System.out.println("線程id: "+ Thread.currentThread().getId());
        System.out.println("線程name: "+ Thread.currentThread().getName());
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if(read != -1){
                    //輸出客戶端發送的數據
                    System.out.println(new String(bytes, 0, read));
                }else{
                    break;
                }
            }

        }catch (Exception e){

        }finally {
            try {
                System.out.println("關閉與客戶端的連接");
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

NIO

Java non-blocking IO的縮寫,同步非阻塞,JDK1.4開始提供。
相關類和接口放在java.nio包下。

NIO三大核心概念

Channel(通道)、Buffer(緩沖區)、Selector(選擇器)

NIO是面向緩沖區的編程

請求數據會先讀取到一個緩沖區,需要時可以在緩沖區中前后移動,這樣增加了處理過程的靈活性。

NIO是非阻塞的

請求要寫入一些數據到某個通道,不需要等待寫完,這個線程就可以去干別的事去。

NIO vs BIO

1.BIO以流的方式處理數據,NIO以塊的方式處理數據,塊I/O的效率比流I/O的效率高很多
2.BIO是阻塞的,NIO是非阻塞的
3.BIO基于字節流和字符流進行操作,NIO基于Channel(通道)和Buffer(緩沖區)進行操作,數據總是從通道讀取到緩沖區或從緩沖區寫入到通道,Selector(選擇器)用于監聽多個通道的事件,比如連接請求、數據到達等,因此使用單個線程就可以監聽多個客戶端通道。

Channel、Buffer和Selector的關系

1.一個線程對應一個Selector
2.一個Channel對應一個Buffer
3.Selector會根據不同的事件,在各個Channel上切換
4.Buffer就是一個內存塊,底層是一個數組
5.數據的讀取寫入都是通過Buffer,Channel是雙向的。


Channel、Buffer和Selector的關系圖
緩沖區(Buffer)

緩沖區的本質其實就是一個可以讀寫數據的內存塊,可以理解成一個容器對象,該對象提供了一系列方法,可以輕松的使用內存塊。

  • Buffer類


    類的層級關系圖

    Buffer中定義了4個屬性來提供關于所包含的數據元素的信息


    Buffer的4個屬性
通道(Channel)

通道可以同時進行讀寫,流只能讀或只能寫,通道可以實現異步讀取數據,通道可以從緩沖讀取數據,也可以寫數據到緩沖。
Channel是一個接口,常用的實現類有FileChannel、DatagramChannel、ServerSocketChannel、SocketChannel等

  • FileChannel

用于本地文件的數據讀寫

常用方法
read : 從通道讀取數據并放入緩沖區
write : 把緩沖區的數據寫入到通道
transferFrom : 從目標通道復制數據到當前通道
transferTo : 把數據從當前通道復制給目標通道

需求: 使用ByteBuffer和FileChannel將"Hello Nio"寫入到a.txt文件中

public static void main(String[] args) throws Exception{

    //1.創建輸出流
    String str = "Hello Nio";
    FileOutputStream fileOutputStream = new FileOutputStream("d:\\a.txt");

    //2.獲取對應的FileChannel
    FileChannel channel = fileOutputStream.getChannel();

    //3.創建一個緩沖區
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    byteBuffer.put(str.getBytes());
    byteBuffer.flip();

    //4.將緩沖區的數據寫入到FileChannel
    channel.write(byteBuffer);
    fileOutputStream.close();

}

需求:使用ByteBuffer和FileChannel,將a.txt文件中的輸出到控制臺

public static void main(String[] args) throws  Exception{
    File file = new File("d:\\a.txt");
    FileInputStream fis = new FileInputStream(file);
    FileChannel channel = fis.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
    channel.read(buffer);
    System.out.println(new String(buffer.array()));
    fis.close();
}

需求: 使用FileChannel和方法write和read完成文件拷貝

public static void main(String[] args) throws Exception{
    FileInputStream fileInputStream = new FileInputStream("d:\\a.txt");
    FileOutputStream fileOutputStream = new FileOutputStream("d:\\b.txt");
    FileChannel channel1 = fileInputStream.getChannel();
    FileChannel channel2 = fileOutputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(512);
    while (true){
        //清空buffer
        buffer.clear();
        int read = channel1.read(buffer);
        if(read == -1){
            break;
        }
        //將buffer中的數據寫入到channel2
        buffer.flip();
        channel2.write(buffer);
    }
    fileInputStream.close();
    fileOutputStream.close();
}

需求: 使用FileChannel和方法transferFrom完成文件拷貝

public static void main(String[] args) throws Exception {
    FileInputStream fileInputStream = new FileInputStream("d:\\a.txt");
    FileOutputStream fileOutputStream = new FileOutputStream("d:\\b.txt");
    FileChannel channel1 = fileInputStream.getChannel();
    FileChannel channel2 = fileOutputStream.getChannel();
    channel2.transferFrom(channel1, 0, channel1.size());
    channel1.close();
    channel2.close();
    fileInputStream.close();
    fileOutputStream.close();
}
  • DatagramChannel

用于UDP的數據讀寫

  • ServerSocketChannel和SocketChannel

用于TCP數據的讀寫

Selector(選擇器)

一個線程處理多個客戶單連接,就會使用Selector,Selector能檢測多個注冊的通道上是否有事件發生,如果事件發送,便獲取事件然后對事件進行相應的處理。并且還可以避免多線程之間上下文切換導致的開銷。

  • 常用方法

open() : 得到一個選擇器對象
select() : 一直阻塞,監控所有注冊的通道,當其中有IO操作,將對應的SelectionKey加入到內部集合并返回
select(1000) : 阻塞1000毫秒
selectedKeys() : 從內部集合中得到所以的SelectionKey
wakeup() : 喚醒selector
selectNow() : 不阻塞,立馬返回

注: 這些方法的使用后面都會有具體的案例講解。

Nio入門案例

需求:實現服務端和客戶端之間的數據通信(非阻塞)

在案例開始先說幾個概念

  • ServerSocketChannel

在服務端監聽新的客戶端Socket連接

方法
open() : 得到一個ServerSocketChannel通道
configureBlocking(boolean block) : 設置阻塞和非阻塞模式,false為非阻塞
accept() : 接受一個連接,返回代表這個連接的通道對象
register() : 注冊一個選擇器并設置監聽事件

  • SocketChannel

網絡IO通道,負責讀寫操作

方法
open() : 獲取一個SocketChannel通道
configureBlocking(boolean block) : 設置阻塞和非阻塞模式,false為非阻塞
connect(SocketAddress remote) : 連接服務器
finishConnect() : 如果連接失敗,使用該方法繼續完成連接
write(ByteBuffer src) : 往通道里寫數據
read(ByteBuffer dst) : 從通道里讀數據
register(Selector sel, int ops, Object att) : 注冊一個選擇器并指定監聽事件,最后一個參數設置共享數據
close() : 關閉通道

  • SelectionKey

表示Selector和網絡通道的注冊關系,共有4種:
OP_ACCEPT : 有新的連接可以accept
OP_CONNECT : 代表連接已建立
OP_READ : 讀操作
OP_WRITE : 寫操作

方法
selector() : 得到與之關聯的Selector對象
channel() : 得到與之關聯的通道
attachment() : 得到與之關聯的Buffer
isAcceptable() : 是否可以accept
isReadable() : 是否可以讀
isWritable() : 是否可以寫

  • 服務端
public class NioServer {

    public static void main(String[] args) throws Exception{
        //1.創建
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //2.創建Selector
        Selector selector = Selector.open();

        //3.綁定端口并監聽端口
        serverSocketChannel.socket().bind(new InetSocketAddress(10000));
        //設置為非阻塞
        serverSocketChannel.configureBlocking(false);

        //4.把serverSocketChannel注冊到selector上, 并監聽OP_ACCEPT事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //5.循環等待客戶端連接
        while (true){
            //等待1秒
            int select = selector.select(1000);
            //等于0, 表示沒有事件發送, 就返回
            if (select == 0){
                System.out.println("服務器等待了1秒, 無連接");
                continue;
            }
            //返回>0, 說明獲取到事件, 獲取所有事件的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍歷集合
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){
                //獲取SelectionKey, 并根據SelectionKey對應的通道所發生的事件類型做對應處理
                SelectionKey key = keyIterator.next();
                //OP_ACCEPT, 有新的客戶端連接了
                if(key.isAcceptable()){
                    //為該客戶端生成一個SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("有新客戶端: "+socketChannel.hashCode());
                    //將SocketChannel設置為非阻塞
                    socketChannel.configureBlocking(false);
                    //將SocketChannel注冊到selector, 監聽時間為OP_READ, 同時給SocketChannel關聯一個Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                //OP_READ, 有新消息
                if(key.isReadable()){
                    //根據key獲取對應的channel
                    SocketChannel channel = (SocketChannel)key.channel();
                    //根據key獲取對應的buffer
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    channel.read(buffer);
                    System.out.println("客戶單消息: "+ new String(buffer.array()));
                }
                //手動從集合中移除當前的selectionKey, 防止重復操作
                keyIterator.remove();
            }
        }
    }

}
  • 客戶端
public class NioClient {

    public static void main(String[] args) throws Exception {

        //1.創建一個網絡通道
        SocketChannel socketChannel = SocketChannel.open();
        //設置非阻塞
        socketChannel.configureBlocking(false);
        //2.連接服務器
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 10000);
        if(!socketChannel.connect(inetSocketAddress)){
            while (!socketChannel.finishConnect()){
                System.out.println("正在連接服務器中....");
            }
        }
        //3.連接成功, 發送數據
        String str = "Hello NioServer";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        socketChannel.write(buffer);
        System.in.read();

    }

}

就整理這么多吧

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容