- I/O 模型
- 阻塞I/O模型(BIO)
- 非阻塞I/O模型
- I/O復(fù)用模型(select/poll;epoll)
- select/poll: 順序掃描fd是否就緒
- epoll: 事件驅(qū)動,mmap同一塊內(nèi)存來減少內(nèi)存復(fù)制
- 信號驅(qū)動I/O模型(何時可以開始I/O操作)
- 數(shù)據(jù)準(zhǔn)備時間內(nèi)進(jìn)程繼續(xù)執(zhí)行,準(zhǔn)備好了執(zhí)行信號處理程序
- 執(zhí)行recvfrom,數(shù)據(jù)復(fù)制(內(nèi)核空間到用戶空間)時阻塞。
- 異步I/O (何時I/O完成)
-
BIO
- 第一種方案 :一個客戶端連接一個線程處理
- 第二種方案: 客戶端連接又線程池來處理
FileChannel 示例
下面是一個使用FileChannel讀取數(shù)據(jù)到Buffer中的示例:
Java代碼
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char) buf.get());
}
buf.clear();
bytesRead = inChannel.read(buf);
}
aFile.close();
注意 buf.flip() 的調(diào)用,首先讀取數(shù)據(jù)到Buffer,然后反轉(zhuǎn)Buffer,接著再從Buffer中讀取數(shù)據(jù)。下一節(jié)會深入講解Buffer的更多細(xì)節(jié)。