java中BIO、NIO、AIO都有啥區(qū)別
一、BIO(Blocking IO,也被稱作old IO)
同步阻塞模型,一個(gè)客戶端連接對(duì)應(yīng)一個(gè)處理線程
對(duì)于每一個(gè)新的網(wǎng)絡(luò)連接都會(huì)分配給一個(gè)線程,每隔線程都獨(dú)立處理自己負(fù)責(zé)的輸入和輸出, 也被稱為Connection Per Thread模式
缺點(diǎn):
1、IO代碼里read操作是阻塞操作,如果連接不做數(shù)據(jù)讀寫操作會(huì)導(dǎo)致線程阻塞,浪費(fèi)資源
2、如果線程很多,會(huì)導(dǎo)致服務(wù)器線程太多,壓力太大,比如C10K問題
所謂c10k問題,指的是服務(wù)器同時(shí)支持成千上萬(wàn)個(gè)客戶端的問題,也就是concurrent 10 000 connection
應(yīng)用場(chǎng)景: BIO 方式適用于連接數(shù)目比較小且固定的架構(gòu), 這種方式對(duì)服務(wù)器資源要求比較高, 但程序簡(jiǎn)單易理解。
示例代碼如下:
Bio服務(wù)端
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * @Title:BIO的服務(wù)端 * @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); //向服務(wù)端發(fā)送數(shù)據(jù) socket.getOutputStream().write("HelloServer".getBytes()); socket.getOutputStream().flush(); System.out.println("向服務(wù)端發(fā)送數(shù)據(jù)結(jié)束"); byte[] bytes = new byte[1024]; //接收服務(wù)端回傳的數(shù)據(jù) socket.getInputStream().read(bytes); System.out.println("接收到服務(wù)端的數(shù)據(jù):" + new String(bytes)); socket.close(); } }
二、NIO(Non Blocking IO,本意也作new IO)
同步非阻塞,服務(wù)器實(shí)現(xiàn)模式為 一個(gè)線程可以處理多個(gè)連接請(qǐng)求(連接),客戶端發(fā)送的連接請(qǐng)求都會(huì)注冊(cè)到多路復(fù)用器selector上,多路復(fù)用器輪詢到連接有IO請(qǐng)求就進(jìn)行處理,是在JDK1.4開始引入的。
應(yīng)用場(chǎng)景:NIO方式適合連接數(shù)目多且連接比較短(輕操作)的架構(gòu),比如聊天服務(wù)器、彈幕系統(tǒng)、服務(wù)器之間通訊,編程相對(duì)復(fù)雜。
NIO 有三大核心組件: Channel(通道), Buffer(緩沖區(qū)),Selector(多路復(fù)用器)
1.channel類似于流,每個(gè)channel對(duì)應(yīng)一個(gè)buffer緩沖區(qū),buffer底層就是個(gè)數(shù)組
2.channel 會(huì)注冊(cè)到selector上,由selector根據(jù)channel讀寫事件的發(fā)生將其交由某個(gè)空閑的線程處理
3.NIO的Buffer和Channel都是可讀也可寫的。
NIO的代碼示例有兩個(gè)
沒有引入多路復(fù)用器的NIO
服務(wù)端
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服務(wù)端 * @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)); //設(shè)置ServerSocketChannel為非阻塞 serverSocket.configureBlocking(false); System.out.println("Nio服務(wù)啟動(dòng)成功"); while(true){ //非阻塞模式accept方法不會(huì)阻塞 /// NIO的非阻塞是由操作系統(tǒng)內(nèi)部實(shí)現(xiàn)的,底層調(diào)用了linux內(nèi)核的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方法不會(huì)阻塞 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("向服務(wù)端發(fā)送數(shù)據(jù)1結(jié)束"); writeBuffer = ByteBuffer.wrap("HelloServer2".getBytes()); socketChannel.write(writeBuffer); System.out.println("向服務(wù)端發(fā)送數(shù)據(jù)2結(jié)束"); writeBuffer = ByteBuffer.wrap("HelloServer3".getBytes()); socketChannel.write(writeBuffer); System.out.println("向服務(wù)端發(fā)送數(shù)據(jù)3結(jié)束"); } }
引入了多路復(fù)用器的NIO
服務(wù)端
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:引入多路復(fù)用器后的NIO服務(wù)端 * @Author:wangchenggong * @Date 2021/4/14 13:57 * @Description * SelectionKey.OP_ACCEPT —— 接收連接繼續(xù)事件,表示服務(wù)器監(jiān)聽到了客戶連接,服務(wù)器可以接收這個(gè)連接了 * SelectionKey.OP_CONNECT —— 連接就緒事件,表示客戶與服務(wù)器的連接已經(jīng)建立成功 * SelectionKey.OP_READ —— 讀就緒事件,表示通道中已經(jīng)有了可讀的數(shù)據(jù),可以執(zhí)行讀操作了(通道目前有數(shù)據(jù),可以進(jìn)行讀操作了) * SelectionKey.OP_WRITE —— 寫就緒事件,表示已經(jīng)可以向通道寫數(shù)據(jù)了(通道目前可以用于寫操作) * * 1.當(dāng)向通道中注冊(cè)SelectionKey.OP_READ事件后,如果客戶端有向緩存中write數(shù)據(jù),下次輪詢時(shí),則會(huì) isReadable()=true; * * 2.當(dāng)向通道中注冊(cè)SelectionKey.OP_WRITE事件后,這時(shí)你會(huì)發(fā)現(xiàn)當(dāng)前輪詢線程中isWritable()一直為true,如果不設(shè)置為其他事件 * @Version */ public class NioSelectorServer { public static void main(String[] args) throws IOException { /** * 創(chuàng)建server端,并且向多路復(fù)用器注冊(cè),讓多路復(fù)用器監(jiān)聽連接事件 */ //創(chuàng)建ServerSocketChannel ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(9000)); //設(shè)置ServerSocketChannel為非阻塞 serverSocket.configureBlocking(false); //打開selector處理channel,即創(chuàng)建epoll Selector selector = Selector.open(); //把ServerSocketChannel注冊(cè)到selector上,并且selector對(duì)客戶端的accept連接操作感興趣 serverSocket.register(selector, SelectionKey.OP_ACCEPT); System.out.println("NioSelectorServer服務(wù)啟動(dòng)成功"); while(true){ //阻塞等待需要處理的事件發(fā)生 selector.select(); //獲取selector中注冊(cè)的全部事件的SelectionKey實(shí)例 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); //遍歷selectionKeys,對(duì)事件進(jìn)行處理 while (iterator.hasNext()){ SelectionKey key = iterator.next(); //如果是OP_ACCEPT事件,則進(jìn)行連接和事件注冊(cè) if(key.isAcceptable()){ ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); //接受客戶端的連接 SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); //把SocketChannel注冊(cè)到selector上,并且selector對(duì)客戶端的read操作(即讀取來(lái)自客戶端的消息)感興趣 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ā)來(lái)的消息,消息內(nèi)容為:"+new String(byteBuffer.array())); }else if(len == -1){ System.out.println("客戶端斷開連接"); //關(guān)閉該客戶端 socketChannel.close(); } } //從事件集合里刪除本次處理的key,防止下次select重復(fù)處理 iterator.remove(); } } /** * NioSelectorServer服務(wù)啟動(dòng)成功 * 客戶端/127.0.0.1:57070連接成功! * 接收到客戶端/127.0.0.1:57070發(fā)來(lái)的消息,消息內(nèi)容為:HelloServer * 客戶端/127.0.0.1:57121連接成功! * 接收到客戶端/127.0.0.1:57121發(fā)來(lái)的消息,消息內(nèi)容為: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:引入多路復(fù)用器后的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(); //要先向多路復(fù)用器注冊(cè),然后才可以跟服務(wù)端進(jìn)行連接 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("服務(wù)器連接成功"); ByteBuffer writeBuffer=ByteBuffer.wrap("HelloServer".getBytes()); sc.write(writeBuffer); System.out.println("向服務(wù)端發(fā)送數(shù)據(jù)結(jié)束"); } } } } /** * 服務(wù)器連接成功 * 向服務(wù)端發(fā)送數(shù)據(jù)結(jié)束 */ } }
三、AIO(Asynchronous IO) 即NIO2.0
異步非阻塞,由操作系統(tǒng)完成后回調(diào)通知服務(wù)端程序啟動(dòng)線程去處理,一般適用于連接數(shù)較多且連接時(shí)間較長(zhǎng)的應(yīng)用。
應(yīng)用場(chǎng)景:AIO方式適用于連接數(shù)目多且連接時(shí)間較長(zhǎng)(重操作)的架構(gòu)(應(yīng)用),JDK7開始支持。
著名的異步網(wǎng)絡(luò)通訊框架netty之所以廢棄了AIO,原因是:在Linux系統(tǒng)上,NIO的底層實(shí)現(xiàn)使用了Epoll,而AIO的底層實(shí)現(xiàn)仍使用Epoll,沒有很好實(shí)現(xiàn)AIO,因此在性能上沒有明顯的優(yōu)勢(shì),而且被JDK封裝了一層不容易深度優(yōu) 化,Linux上AIO還不夠成熟
AIO示例代碼如下:
服務(wù)端
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服務(wù)端 * @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從寫模式切換到讀模式 //如果沒有,就是從文件最后開始讀取的,當(dāng)然讀出來(lái)的都是byte=0時(shí)候的字符。通過buffer.flip();這個(gè)語(yǔ)句,就能把buffer的當(dāng)前位置更改為buffer緩沖區(qū)的第一個(gè)位置 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)); } } }
四、總結(jié)
BIO | NIO | AIO | |
IO模型 | 同步阻塞 | 同步非阻塞 | 異步非阻塞 |
編程難度 | 簡(jiǎn)單 | 復(fù)雜 | 復(fù)雜 |
可靠性 好 | 差 | 好 | 好 |
吞吐量 | 低 | 高 | 高 |
到此這篇關(guān)于java中BIO、NIO、AIO都有啥區(qū)別的文章就介紹到這了,更多相關(guān)java中BIO、NIO、AIO的區(qū)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- JavaIO模型中的BIO,NIO和AIO詳解
- Java中BIO、NIO和AIO的區(qū)別、原理與用法
- Java框架解說之BIO NIO AIO不同IO模型演進(jìn)之路
- Java BIO,NIO,AIO總結(jié)
- 淺談Java中BIO、NIO和AIO的區(qū)別和應(yīng)用場(chǎng)景
- 詳解Java 網(wǎng)絡(luò)IO編程總結(jié)(BIO、NIO、AIO均含完整實(shí)例代碼)
- Java中BIO、NIO、AIO的理解
- Java中網(wǎng)絡(luò)IO的實(shí)現(xiàn)方式(BIO、NIO、AIO)介紹
- Java中AIO、BIO、NIO應(yīng)用場(chǎng)景及區(qū)別
相關(guān)文章
Idea設(shè)置spring boot應(yīng)用配置參數(shù)的兩種方式
本文通過兩個(gè)方式介紹Idea設(shè)置spring boot應(yīng)用配置參數(shù),一種是配置VM options的參數(shù)時(shí)要以:-DparamName的格式設(shè)置參數(shù),第二種可以參考下本文詳細(xì)設(shè)置,感興趣的朋友跟隨小編一起看看吧2023-11-11java配置dbcp連接池(數(shù)據(jù)庫(kù)連接池)示例分享
java配置dbcp連接池示例分享,大家參考使用吧2013-12-12SpringBoot日志框架之Log4j2快速入門與參數(shù)詳解
本文介紹了SpringBoot日志框架log4j2的基本使用和配置方法,包括將日志輸出到控制臺(tái)、文件、Elasticsearch和Kafka,多個(gè)輸出目的地的配置,異步日志記錄器的使用以及l(fā)og4j2.xml配置文件的詳細(xì)語(yǔ)法和參數(shù)含義,需要的朋友可以參考下2023-05-05Java string類型轉(zhuǎn)換成map代碼實(shí)例
這篇文章主要介紹了Java string類型轉(zhuǎn)換成map代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03springboot中json對(duì)象中對(duì)Long類型和String類型相互轉(zhuǎn)換
與前端聯(lián)調(diào)接口時(shí),后端一些字段設(shè)計(jì)為L(zhǎng)ong類型,這樣就有可能導(dǎo)致前端缺失精度,這時(shí)候我們就需要將Long類型返回給前端時(shí)做數(shù)據(jù)類型轉(zhuǎn)換,本文主要介紹了springboot中json對(duì)象中對(duì)Long類型和String類型相互轉(zhuǎn)換,感興趣的可以了解一下2023-11-11Java實(shí)戰(zhàn)小技巧之?dāng)?shù)組與list互轉(zhuǎn)
在Java中,經(jīng)常遇到需要List與數(shù)組互相轉(zhuǎn)換的場(chǎng)景,下面這篇文章主要給大家介紹了關(guān)于Java實(shí)戰(zhàn)小技巧之?dāng)?shù)組與list互轉(zhuǎn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08