I/O模型
I/O模型簡單理解就是用什么樣的通道進(jìn)行數(shù)據(jù)的發(fā)生和接收,這個(gè)很大程度上覺得了程序通信的性能。
Java有三種網(wǎng)絡(luò)編程模型,分別是BIO、NIO和NIO。
BIO
同步并阻塞,一個(gè)連接一個(gè)線程,即客戶端有請求服務(wù)端就會(huì)開啟一個(gè)線程進(jìn)行處理。缺點(diǎn)就是如果這個(gè)連接不做任何事情就會(huì)造成不必要的線程開銷。
BIO示意圖
NIO
同步非阻塞,一個(gè)線程處理多個(gè)請求,客戶端請求會(huì)注冊到多路復(fù)用器上,多路復(fù)用器輪詢到連接有I/O請求就進(jìn)行處理。
NIO示意圖
AIO
異步非阻塞IO,AIO引入異步通道的概念,采用了Proactor模式,簡化了程序編寫,有效的請求才啟動(dòng)線程,它的特點(diǎn)是先由操作系統(tǒng)完成后才通知服務(wù)端程序啟動(dòng)程序去處理,一般適合用于連接數(shù)較多且連接時(shí)間較長的應(yīng)用。不常用,所以這里不做過多講解。
三種IO模型的應(yīng)用場景
BIO適合于鏈接數(shù)目較少且固定的架構(gòu),這種方式對(duì)服務(wù)器的資源要求較高,JDK1.4之前的唯一選擇,程序簡單易理解。
NIO適合于連接數(shù)目較多且連接比較短的架構(gòu),比如聊天服務(wù)器、服務(wù)期間通信等,編程較復(fù)雜。JDK1.4新增。
AIO適用于連接數(shù)多且連接時(shí)間較長的架構(gòu)。編程較復(fù)雜,JDK1.7開始支持。
BIO
Java BIO就是傳統(tǒng)的Java io編程,相關(guān)類和接口都在java.io包下。前面已經(jīng)說過,它是同步阻塞的,一個(gè)連接就啟動(dòng)一個(gè)線程,比較浪費(fèi)服務(wù)器資源。
需求: 使用BIO實(shí)現(xiàn)一個(gè)服務(wù)器端,監(jiān)聽10000端口,當(dāng)客戶端連接時(shí),就啟動(dòng)一個(gè)線程與之通訊,要求使用線程池。
public class BioServer {
public static void main(String[] args) throws Exception {
//1.創(chuàng)建一個(gè)線程池
ExecutorService pool = Executors.newCachedThreadPool();
//2.如果有請求, 就創(chuàng)建一個(gè)線程與之通信
//創(chuàng)建服務(wù)端
ServerSocket serverSocket = new ServerSocket(10000);
System.out.println("服務(wù)器啟動(dòng).");
while (true){
System.out.println("等待連接......");
final Socket socket = serverSocket.accept();
System.out.println("有新連接");
//創(chuàng)建一個(gè)線程與之通信
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){
//輸出客戶端發(fā)送的數(shù)據(jù)
System.out.println(new String(bytes, 0, read));
}else{
break;
}
}
}catch (Exception e){
}finally {
try {
System.out.println("關(guān)閉與客戶端的連接");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
NIO
Java non-blocking IO的縮寫,同步非阻塞,JDK1.4開始提供。
相關(guān)類和接口放在java.nio包下。
NIO三大核心概念
Channel(通道)、Buffer(緩沖區(qū))、Selector(選擇器)
NIO是面向緩沖區(qū)的編程
請求數(shù)據(jù)會(huì)先讀取到一個(gè)緩沖區(qū),需要時(shí)可以在緩沖區(qū)中前后移動(dòng),這樣增加了處理過程的靈活性。
NIO是非阻塞的
請求要寫入一些數(shù)據(jù)到某個(gè)通道,不需要等待寫完,這個(gè)線程就可以去干別的事去。
NIO vs BIO
1.BIO以流的方式處理數(shù)據(jù),NIO以塊的方式處理數(shù)據(jù),塊I/O的效率比流I/O的效率高很多
2.BIO是阻塞的,NIO是非阻塞的
3.BIO基于字節(jié)流和字符流進(jìn)行操作,NIO基于Channel(通道)和Buffer(緩沖區(qū))進(jìn)行操作,數(shù)據(jù)總是從通道讀取到緩沖區(qū)或從緩沖區(qū)寫入到通道,Selector(選擇器)用于監(jiān)聽多個(gè)通道的事件,比如連接請求、數(shù)據(jù)到達(dá)等,因此使用單個(gè)線程就可以監(jiān)聽多個(gè)客戶端通道。
Channel、Buffer和Selector的關(guān)系
1.一個(gè)線程對(duì)應(yīng)一個(gè)Selector
2.一個(gè)Channel對(duì)應(yīng)一個(gè)Buffer
3.Selector會(huì)根據(jù)不同的事件,在各個(gè)Channel上切換
4.Buffer就是一個(gè)內(nèi)存塊,底層是一個(gè)數(shù)組
5.數(shù)據(jù)的讀取寫入都是通過Buffer,Channel是雙向的。
Channel、Buffer和Selector的關(guān)系圖
緩沖區(qū)(Buffer)
緩沖區(qū)的本質(zhì)其實(shí)就是一個(gè)可以讀寫數(shù)據(jù)的內(nèi)存塊,可以理解成一個(gè)容器對(duì)象,該對(duì)象提供了一系列方法,可以輕松的使用內(nèi)存塊。
-
Buffer類
類的層級(jí)關(guān)系圖
Buffer中定義了4個(gè)屬性來提供關(guān)于所包含的數(shù)據(jù)元素的信息
Buffer的4個(gè)屬性
通道(Channel)
通道可以同時(shí)進(jìn)行讀寫,流只能讀或只能寫,通道可以實(shí)現(xiàn)異步讀取數(shù)據(jù),通道可以從緩沖讀取數(shù)據(jù),也可以寫數(shù)據(jù)到緩沖。
Channel是一個(gè)接口,常用的實(shí)現(xiàn)類有FileChannel、DatagramChannel、ServerSocketChannel、SocketChannel等
- FileChannel
用于本地文件的數(shù)據(jù)讀寫
常用方法
read : 從通道讀取數(shù)據(jù)并放入緩沖區(qū)
write : 把緩沖區(qū)的數(shù)據(jù)寫入到通道
transferFrom : 從目標(biāo)通道復(fù)制數(shù)據(jù)到當(dāng)前通道
transferTo : 把數(shù)據(jù)從當(dāng)前通道復(fù)制給目標(biāo)通道
需求: 使用ByteBuffer和FileChannel將"Hello Nio"寫入到a.txt文件中
public static void main(String[] args) throws Exception{
//1.創(chuàng)建輸出流
String str = "Hello Nio";
FileOutputStream fileOutputStream = new FileOutputStream("d:\\a.txt");
//2.獲取對(duì)應(yīng)的FileChannel
FileChannel channel = fileOutputStream.getChannel();
//3.創(chuàng)建一個(gè)緩沖區(qū)
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put(str.getBytes());
byteBuffer.flip();
//4.將緩沖區(qū)的數(shù)據(jù)寫入到FileChannel
channel.write(byteBuffer);
fileOutputStream.close();
}
需求:使用ByteBuffer和FileChannel,將a.txt文件中的輸出到控制臺(tái)
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中的數(shù)據(jù)寫入到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的數(shù)據(jù)讀寫
- ServerSocketChannel和SocketChannel
用于TCP數(shù)據(jù)的讀寫
Selector(選擇器)
一個(gè)線程處理多個(gè)客戶單連接,就會(huì)使用Selector,Selector能檢測多個(gè)注冊的通道上是否有事件發(fā)生,如果事件發(fā)送,便獲取事件然后對(duì)事件進(jìn)行相應(yīng)的處理。并且還可以避免多線程之間上下文切換導(dǎo)致的開銷。
- 常用方法
open() : 得到一個(gè)選擇器對(duì)象
select() : 一直阻塞,監(jiān)控所有注冊的通道,當(dāng)其中有IO操作,將對(duì)應(yīng)的SelectionKey加入到內(nèi)部集合并返回
select(1000) : 阻塞1000毫秒
selectedKeys() : 從內(nèi)部集合中得到所以的SelectionKey
wakeup() : 喚醒selector
selectNow() : 不阻塞,立馬返回注: 這些方法的使用后面都會(huì)有具體的案例講解。
Nio入門案例
需求:實(shí)現(xiàn)服務(wù)端和客戶端之間的數(shù)據(jù)通信(非阻塞)
在案例開始先說幾個(gè)概念
- ServerSocketChannel
在服務(wù)端監(jiān)聽新的客戶端Socket連接
方法
open() : 得到一個(gè)ServerSocketChannel通道
configureBlocking(boolean block) : 設(shè)置阻塞和非阻塞模式,false為非阻塞
accept() : 接受一個(gè)連接,返回代表這個(gè)連接的通道對(duì)象
register() : 注冊一個(gè)選擇器并設(shè)置監(jiān)聽事件
- SocketChannel
網(wǎng)絡(luò)IO通道,負(fù)責(zé)讀寫操作
方法
open() : 獲取一個(gè)SocketChannel通道
configureBlocking(boolean block) : 設(shè)置阻塞和非阻塞模式,false為非阻塞
connect(SocketAddress remote) : 連接服務(wù)器
finishConnect() : 如果連接失敗,使用該方法繼續(xù)完成連接
write(ByteBuffer src) : 往通道里寫數(shù)據(jù)
read(ByteBuffer dst) : 從通道里讀數(shù)據(jù)
register(Selector sel, int ops, Object att) : 注冊一個(gè)選擇器并指定監(jiān)聽事件,最后一個(gè)參數(shù)設(shè)置共享數(shù)據(jù)
close() : 關(guān)閉通道
- SelectionKey
表示Selector和網(wǎng)絡(luò)通道的注冊關(guān)系,共有4種:
OP_ACCEPT : 有新的連接可以accept
OP_CONNECT : 代表連接已建立
OP_READ : 讀操作
OP_WRITE : 寫操作方法
selector() : 得到與之關(guān)聯(lián)的Selector對(duì)象
channel() : 得到與之關(guān)聯(lián)的通道
attachment() : 得到與之關(guān)聯(lián)的Buffer
isAcceptable() : 是否可以accept
isReadable() : 是否可以讀
isWritable() : 是否可以寫
- 服務(wù)端
public class NioServer {
public static void main(String[] args) throws Exception{
//1.創(chuàng)建
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2.創(chuàng)建Selector
Selector selector = Selector.open();
//3.綁定端口并監(jiān)聽端口
serverSocketChannel.socket().bind(new InetSocketAddress(10000));
//設(shè)置為非阻塞
serverSocketChannel.configureBlocking(false);
//4.把serverSocketChannel注冊到selector上, 并監(jiān)聽OP_ACCEPT事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//5.循環(huán)等待客戶端連接
while (true){
//等待1秒
int select = selector.select(1000);
//等于0, 表示沒有事件發(fā)送, 就返回
if (select == 0){
System.out.println("服務(wù)器等待了1秒, 無連接");
continue;
}
//返回>0, 說明獲取到事件, 獲取所有事件的集合
Set<SelectionKey> selectionKeys = selector.selectedKeys();
//遍歷集合
Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
while (keyIterator.hasNext()){
//獲取SelectionKey, 并根據(jù)SelectionKey對(duì)應(yīng)的通道所發(fā)生的事件類型做對(duì)應(yīng)處理
SelectionKey key = keyIterator.next();
//OP_ACCEPT, 有新的客戶端連接了
if(key.isAcceptable()){
//為該客戶端生成一個(gè)SocketChannel
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("有新客戶端: "+socketChannel.hashCode());
//將SocketChannel設(shè)置為非阻塞
socketChannel.configureBlocking(false);
//將SocketChannel注冊到selector, 監(jiān)聽時(shí)間為OP_READ, 同時(shí)給SocketChannel關(guān)聯(lián)一個(gè)Buffer
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
//OP_READ, 有新消息
if(key.isReadable()){
//根據(jù)key獲取對(duì)應(yīng)的channel
SocketChannel channel = (SocketChannel)key.channel();
//根據(jù)key獲取對(duì)應(yīng)的buffer
ByteBuffer buffer = (ByteBuffer)key.attachment();
channel.read(buffer);
System.out.println("客戶單消息: "+ new String(buffer.array()));
}
//手動(dòng)從集合中移除當(dāng)前的selectionKey, 防止重復(fù)操作
keyIterator.remove();
}
}
}
}
- 客戶端
public class NioClient {
public static void main(String[] args) throws Exception {
//1.創(chuàng)建一個(gè)網(wǎng)絡(luò)通道
SocketChannel socketChannel = SocketChannel.open();
//設(shè)置非阻塞
socketChannel.configureBlocking(false);
//2.連接服務(wù)器
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 10000);
if(!socketChannel.connect(inetSocketAddress)){
while (!socketChannel.finishConnect()){
System.out.println("正在連接服務(wù)器中....");
}
}
//3.連接成功, 發(fā)送數(shù)據(jù)
String str = "Hello NioServer";
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
socketChannel.write(buffer);
System.in.read();
}
}
就整理這么多吧