欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java中BIO、NIO、AIO都有啥區(qū)別

 更新時間:2021年04月16日 16:27:04   作者:Java面試一問一答(公眾號)  
這篇文章主要介紹了java中BIO、NIO、AIO都有啥區(qū)別,IO模型就是說用什么樣的通道進行數(shù)據(jù)的發(fā)送和接收,Java共支持3種網絡編程IO模式:BIO,NIO,AIO,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有非常好的幫助,需要的朋友可以參考下

一、BIO(Blocking IO,也被稱作old IO)

同步阻塞模型,一個客戶端連接對應一個處理線程

對于每一個新的網絡連接都會分配給一個線程,每隔線程都獨立處理自己負責的輸入和輸出, 也被稱為Connection Per Thread模式

在這里插入圖片描述

缺點:

1、IO代碼里read操作是阻塞操作,如果連接不做數(shù)據(jù)讀寫操作會導致線程阻塞,浪費資源

2、如果線程很多,會導致服務器線程太多,壓力太大,比如C10K問題

所謂c10k問題,指的是服務器同時支持成千上萬個客戶端的問題,也就是concurrent 10 000 connection

應用場景: BIO 方式適用于連接數(shù)目比較小且固定的架構, 這種方式對服務器資源要求比較高, 但程序簡單易理解。

示例代碼如下:

Bio服務端

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Title:BIO的服務端
 * @Author:wangchenggong
 * @Date 2021/4/13 9:41
 * @Description
 * @Version
 */
public class SocketServer {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);
        while (true){
            System.out.println("等待連接...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("客戶端"+clientSocket.getRemoteSocketAddress()+"連接了!");

            handle(clientSocket);
        }

    }

    private static void handle(Socket clientSocket)  throws IOException{
        byte[] bytes = new byte[1024];
        int read = clientSocket.getInputStream().read(bytes);
        System.out.println("read 客戶端"+clientSocket.getRemoteSocketAddress()+"數(shù)據(jù)完畢");
        if(read != -1){
            System.out.println("接收到客戶端的數(shù)據(jù):" + new String(bytes, 0, read));
        }
        clientSocket.getOutputStream().write("HelloClient".getBytes());
        clientSocket.getOutputStream().flush();
    }

}

Bio客戶端

import java.io.IOException;
import java.net.Socket;

/**
 * @Title:BIO的客戶端
 * @Author:wangchenggong
 * @Date 2021/4/13 9:49
 * @Description
 * @Version
 */
public class SocketClient {

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

        Socket socket = new Socket("localhost", 9000);
        //向服務端發(fā)送數(shù)據(jù)
        socket.getOutputStream().write("HelloServer".getBytes());
        socket.getOutputStream().flush();
        System.out.println("向服務端發(fā)送數(shù)據(jù)結束");

        byte[] bytes = new byte[1024];
        //接收服務端回傳的數(shù)據(jù)
        socket.getInputStream().read(bytes);

        System.out.println("接收到服務端的數(shù)據(jù):" + new String(bytes));
        socket.close();
    }
}

二、NIO(Non Blocking IO,本意也作new IO)

同步非阻塞,服務器實現(xiàn)模式為 一個線程可以處理多個連接請求(連接),客戶端發(fā)送的連接請求都會注冊到多路復用器selector上,多路復用器輪詢到連接有IO請求就進行處理,是在JDK1.4開始引入的。

應用場景:NIO方式適合連接數(shù)目多且連接比較短(輕操作)的架構,比如聊天服務器、彈幕系統(tǒng)、服務器之間通訊,編程相對復雜。

在這里插入圖片描述

NIO 有三大核心組件: Channel(通道), Buffer(緩沖區(qū)),Selector(多路復用器)

1.channel類似于流,每個channel對應一個buffer緩沖區(qū),buffer底層就是個數(shù)組

2.channel 會注冊到selector上,由selector根據(jù)channel讀寫事件的發(fā)生將其交由某個空閑的線程處理

3.NIO的Buffer和Channel都是可讀也可寫的。

NIO的代碼示例有兩個

沒有引入多路復用器的NIO

服務端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Title:Nio服務端
 * @Author:wangchenggong
 * @Date 2021/4/14 11:04
 * @Description
 * @Version
 */
public class NioServer {

    /**
     * 保存客戶端連接
     */
    static List<SocketChannel> channelList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //創(chuàng)建Nio ServerSocketChannel
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        //設置ServerSocketChannel為非阻塞
        serverSocket.configureBlocking(false);
        System.out.println("Nio服務啟動成功");

        while(true){
            //非阻塞模式accept方法不會阻塞
            /// NIO的非阻塞是由操作系統(tǒng)內部實現(xiàn)的,底層調用了linux內核的accept函數(shù)
            SocketChannel socketChannel = serverSocket.accept();
            if(socketChannel != null){
                System.out.println("連接成功");
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }

            Iterator<SocketChannel> iterator = channelList.iterator();
            while(iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                //非阻塞模式read方法不會阻塞
                int len = sc.read(byteBuffer);

                if(len > 0){
                    System.out.println("接收到消息:" + new String(byteBuffer.array()));
                }else if(len == -1){
                    iterator.remove();
                    System.out.println("客戶端斷開連接");
                }
            }

        }
    }
}

客戶端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Title:Nio客戶端
 * @Author:wangchenggong
 * @Date 2021/4/14 11:36
 * @Description
 * @Version
 */
public class NioClient {

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

        SocketChannel socketChannel=SocketChannel.open(new InetSocketAddress("localhost", 9000));
        socketChannel.configureBlocking(false);


        ByteBuffer writeBuffer=ByteBuffer.wrap("HelloServer1".getBytes());
        socketChannel.write(writeBuffer);
        System.out.println("向服務端發(fā)送數(shù)據(jù)1結束");

        writeBuffer = ByteBuffer.wrap("HelloServer2".getBytes());
        socketChannel.write(writeBuffer);
        System.out.println("向服務端發(fā)送數(shù)據(jù)2結束");

        writeBuffer = ByteBuffer.wrap("HelloServer3".getBytes());
        socketChannel.write(writeBuffer);
        System.out.println("向服務端發(fā)送數(shù)據(jù)3結束");
    }


}

引入了多路復用器的NIO

服務端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @Title:引入多路復用器后的NIO服務端
 * @Author:wangchenggong
 * @Date 2021/4/14 13:57
 * @Description
 * SelectionKey.OP_ACCEPT —— 接收連接繼續(xù)事件,表示服務器監(jiān)聽到了客戶連接,服務器可以接收這個連接了
 * SelectionKey.OP_CONNECT —— 連接就緒事件,表示客戶與服務器的連接已經建立成功
 * SelectionKey.OP_READ —— 讀就緒事件,表示通道中已經有了可讀的數(shù)據(jù),可以執(zhí)行讀操作了(通道目前有數(shù)據(jù),可以進行讀操作了)
 * SelectionKey.OP_WRITE —— 寫就緒事件,表示已經可以向通道寫數(shù)據(jù)了(通道目前可以用于寫操作)
 *
 * 1.當向通道中注冊SelectionKey.OP_READ事件后,如果客戶端有向緩存中write數(shù)據(jù),下次輪詢時,則會 isReadable()=true;
 *
 * 2.當向通道中注冊SelectionKey.OP_WRITE事件后,這時你會發(fā)現(xiàn)當前輪詢線程中isWritable()一直為true,如果不設置為其他事件
 * @Version
 */
public class NioSelectorServer {

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

        /**
         * 創(chuàng)建server端,并且向多路復用器注冊,讓多路復用器監(jiān)聽連接事件
         */
        //創(chuàng)建ServerSocketChannel
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        //設置ServerSocketChannel為非阻塞
        serverSocket.configureBlocking(false);
        //打開selector處理channel,即創(chuàng)建epoll
        Selector selector = Selector.open();
        //把ServerSocketChannel注冊到selector上,并且selector對客戶端的accept連接操作感興趣
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("NioSelectorServer服務啟動成功");


        while(true){
            //阻塞等待需要處理的事件發(fā)生
            selector.select();

            //獲取selector中注冊的全部事件的SelectionKey實例
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            //遍歷selectionKeys,對事件進行處理
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //如果是OP_ACCEPT事件,則進行連接和事件注冊
                if(key.isAcceptable()){
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    //接受客戶端的連接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //把SocketChannel注冊到selector上,并且selector對客戶端的read操作(即讀取來自客戶端的消息)感興趣
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println("客戶端"+socketChannel.getRemoteAddress()+"連接成功!");

                }else if(key.isReadable()){
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int len = socketChannel.read(byteBuffer);
                    if(len > 0){
                        System.out.println("接收到客戶端"+socketChannel.getRemoteAddress()+"發(fā)來的消息,消息內容為:"+new String(byteBuffer.array()));
                    }else if(len == -1){
                        System.out.println("客戶端斷開連接");
                        //關閉該客戶端
                        socketChannel.close();
                    }
                }
                //從事件集合里刪除本次處理的key,防止下次select重復處理
                iterator.remove();
            }

        }

        /**
         * NioSelectorServer服務啟動成功
         * 客戶端/127.0.0.1:57070連接成功!
         * 接收到客戶端/127.0.0.1:57070發(fā)來的消息,消息內容為:HelloServer
         * 客戶端/127.0.0.1:57121連接成功!
         * 接收到客戶端/127.0.0.1:57121發(fā)來的消息,消息內容為:HelloServer
         */

    }
}

客戶端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Title:引入多路復用器后的NIO客戶端
 * @Author:wangchenggong
 * @Date 2021/4/14 14:39
 * @Description
 * @Version
 */
public class NioSelectorClient {

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

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        //要先向多路復用器注冊,然后才可以跟服務端進行連接
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress("localhost", 9000));

        while (true){
            selector.select();
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isConnectable()){
                    SocketChannel sc = (SocketChannel) key.channel();
                    if (sc.finishConnect()){
                        System.out.println("服務器連接成功");

                        ByteBuffer writeBuffer=ByteBuffer.wrap("HelloServer".getBytes());
                        sc.write(writeBuffer);
                        System.out.println("向服務端發(fā)送數(shù)據(jù)結束");
                    }
                }
            }
        }

        /**
         * 服務器連接成功
         * 向服務端發(fā)送數(shù)據(jù)結束
         */

    }
}

三、AIO(Asynchronous IO) 即NIO2.0

異步非阻塞,由操作系統(tǒng)完成后回調通知服務端程序啟動線程去處理,一般適用于連接數(shù)較多且連接時間較長的應用。

應用場景:AIO方式適用于連接數(shù)目多且連接時間較長(重操作)的架構(應用),JDK7開始支持。

著名的異步網絡通訊框架netty之所以廢棄了AIO,原因是:在Linux系統(tǒng)上,NIO的底層實現(xiàn)使用了Epoll,而AIO的底層實現(xiàn)仍使用Epoll,沒有很好實現(xiàn)AIO,因此在性能上沒有明顯的優(yōu)勢,而且被JDK封裝了一層不容易深度優(yōu) 化,Linux上AIO還不夠成熟

AIO示例代碼如下:

服務端

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @Title:Aio服務端
 * @Author:wangchenggong
 * @Date 2021/4/14 17:05
 * @Description
 * @Version
 */
public class AioServer {

    public static void main(String[] args) throws Exception {
        final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(9000));
        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                try{
                    System.out.println("2--"+Thread.currentThread().getName());
                    //接收客戶端連接
                    serverChannel.accept(attachment,this);
                    System.out.println("客戶端"+socketChannel.getRemoteAddress()+"已連接");

                    ByteBuffer buffer = ByteBuffer.allocate(128);
                    socketChannel.read(buffer, null, new CompletionHandler<Integer, Object>() {
                        @Override
                        public void completed(Integer result, Object attachment) {
                            System.out.println("3--"+Thread.currentThread().getName());
                            //flip方法將Buffer從寫模式切換到讀模式
                            //如果沒有,就是從文件最后開始讀取的,當然讀出來的都是byte=0時候的字符。通過buffer.flip();這個語句,就能把buffer的當前位置更改為buffer緩沖區(qū)的第一個位置
                            buffer.flip();
                            System.out.println(new String(buffer.array(), 0, result));
                            socketChannel.write(ByteBuffer.wrap("hello Aio Client!".getBytes()));
                        }

                        @Override
                        public void failed(Throwable exc, Object attachment) {
                            exc.printStackTrace();
                        }
                    });

                }catch(Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });

        System.out.println("1‐‐main"+Thread.currentThread().getName());
        Thread.sleep(Integer.MAX_VALUE);
    }
    /**
     * 1‐‐mainmain
     * 2--Thread-9
     * 客戶端/127.0.0.1:54821已連接
     * 3--Thread-8
     * hello AIO server !
     * 2--Thread-9
     * 客戶端/127.0.0.1:54942已連接
     * 3--Thread-7
     * hello AIO server !
     */

}

客戶端

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;

/**
 * @Title:Aio客戶端
 * @Author:wangchenggong
 * @Date 2021/4/14 16:56
 * @Description
 * @Version
 */
public class AioClient {

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

        //創(chuàng)建Aio客戶端
        AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 9000)).get();
        //發(fā)送消息
        socketChannel.write(ByteBuffer.wrap("hello AIO server !".getBytes()));
        //接收消息
        ByteBuffer buffer = ByteBuffer.allocate(128);
        Integer len = socketChannel.read(buffer).get();
        if(len != -1){
            //客戶端收到消息:hello Aio Client!
            System.out.println("客戶端收到消息:"+new String(buffer.array(), 0, len));
        }
    }


}

四、總結

BIO NIO AIO
IO模型 同步阻塞 同步非阻塞 異步非阻塞
編程難度 簡單 復雜 復雜
可靠性 好
吞吐量

到此這篇關于java中BIO、NIO、AIO都有啥區(qū)別的文章就介紹到這了,更多相關java中BIO、NIO、AIO的區(qū)別內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Idea設置spring boot應用配置參數(shù)的兩種方式

    Idea設置spring boot應用配置參數(shù)的兩種方式

    本文通過兩個方式介紹Idea設置spring boot應用配置參數(shù),一種是配置VM options的參數(shù)時要以:-DparamName的格式設置參數(shù),第二種可以參考下本文詳細設置,感興趣的朋友跟隨小編一起看看吧
    2023-11-11
  • springboot各種下載文件的方式匯總

    springboot各種下載文件的方式匯總

    下載功能其實就是用戶輸入指定文件路徑信息,然后把文件返回給用戶,下面這篇文章主要給大家介紹了關于springboot各種下載文件的方式,需要的朋友可以參考下
    2022-10-10
  • java配置dbcp連接池(數(shù)據(jù)庫連接池)示例分享

    java配置dbcp連接池(數(shù)據(jù)庫連接池)示例分享

    java配置dbcp連接池示例分享,大家參考使用吧
    2013-12-12
  • SpringBoot日志框架之Log4j2快速入門與參數(shù)詳解

    SpringBoot日志框架之Log4j2快速入門與參數(shù)詳解

    本文介紹了SpringBoot日志框架log4j2的基本使用和配置方法,包括將日志輸出到控制臺、文件、Elasticsearch和Kafka,多個輸出目的地的配置,異步日志記錄器的使用以及l(fā)og4j2.xml配置文件的詳細語法和參數(shù)含義,需要的朋友可以參考下
    2023-05-05
  • java的多線程高并發(fā)詳解

    java的多線程高并發(fā)詳解

    這篇文章主要介紹了java的多線程高并發(fā)詳解,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-04-04
  • Java string類型轉換成map代碼實例

    Java string類型轉換成map代碼實例

    這篇文章主要介紹了Java string類型轉換成map代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • springboot中json對象中對Long類型和String類型相互轉換

    springboot中json對象中對Long類型和String類型相互轉換

    與前端聯(lián)調接口時,后端一些字段設計為Long類型,這樣就有可能導致前端缺失精度,這時候我們就需要將Long類型返回給前端時做數(shù)據(jù)類型轉換,本文主要介紹了springboot中json對象中對Long類型和String類型相互轉換,感興趣的可以了解一下
    2023-11-11
  • Java實戰(zhàn)小技巧之數(shù)組與list互轉

    Java實戰(zhàn)小技巧之數(shù)組與list互轉

    在Java中,經常遇到需要List與數(shù)組互相轉換的場景,下面這篇文章主要給大家介紹了關于Java實戰(zhàn)小技巧之數(shù)組與list互轉的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下
    2021-08-08
  • Java內存區(qū)域和內存模型講解

    Java內存區(qū)域和內存模型講解

    今天小編就為大家分享一篇關于Java內存區(qū)域和內存模型講解,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • SpringBoot中RabbitMQ集群的搭建詳解

    SpringBoot中RabbitMQ集群的搭建詳解

    單個的?RabbitMQ?肯定無法實現(xiàn)高可用,要想高可用,還得上集群。這篇文章主要介紹了SpringBoot中RabbitMQ集群的兩種模式的搭建:普通集群搭建和鏡像集群搭建,需要的朋友可以參考一下
    2021-12-12

最新評論