netty:IO模型
生活随笔
收集整理的這篇文章主要介紹了
netty:IO模型
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
BIO,NIO模型
BIO代碼實現(xiàn)
import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;public class BIOServer {public static void main(String[] args) throws IOException{ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();ServerSocket serverSocket = new ServerSocket(8888);System.out.println("服務器啟動...");while(true){// 監(jiān)聽final Socket socket = serverSocket.accept();System.out.println("連接一個客戶端...");newCachedThreadPool.execute(new Runnable(){@Overridepublic void run() {handler(socket);}});}}public static void handler(Socket socket){try {byte[] bytes = new byte[1024];InputStream ins = socket.getInputStream();while(true){int readLength = ins.read(bytes);if(-1 != readLength){System.out.println("線程: " + Thread.currentThread().getName() + " ");System.out.println(new String(bytes,0,readLength));}else{break;}}} catch (Exception e) {e.printStackTrace();}finally{try {socket.close();} catch (IOException e) {e.printStackTrace();}}} }使用telnet連接ServerSocket
telnet 127.0.0.1 8888
NIO(non-blocking IO)同步非阻塞
NIO有三大核心部分, Channel(通道), Buffer(緩沖區(qū)), Selector(選擇器)
1.每個Channel都會對應一個Buffer。
2.Selector對應一個線程,一個線程對應多個channel。
3.程序切換到哪個channel是由事件決定的,Event(事件)就是一個重要的概念。
4.Buffer是一個內存塊,底層是有一個數(shù)組。
5.數(shù)據(jù)的讀取寫入是通過Buffer,這個和BIO不一樣, BIO中是通過輸入流,輸出流兩個流進行讀取,寫入的。而NIO僅僅只通過Buffer就完成讀取寫入。
6.Channel也是雙向的,可以返回底層操作系統(tǒng)的情況,比如linux底層的操作系統(tǒng)通道就是雙向的。
buffer
Channel(通道)
FileChannel用于文件的數(shù)據(jù)讀寫。
DatagramChannel用于UDP的數(shù)據(jù)讀寫。
ServerSocketChannel和SocketChannel用于TCP的數(shù)據(jù)讀寫。
向本地文件寫數(shù)據(jù)
import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;public class NIOFileChannel01 {public static void main(String[] args) throws Exception{String str = "hello, 風云爭霸ddd";// 創(chuàng)建一個輸出流FileOutputStream fos = new FileOutputStream("C:\\Users\\haha\\Desktop\\2.txt");// 通過FileOutputStream 獲取對應的 FileChannel// 這個fileChannel的真是類型是FileChannelImplFileChannel fileChannel = fos.getChannel();// 創(chuàng)建一個緩沖區(qū) ByteBufferByteBuffer bf = ByteBuffer.allocate(1024);// 將str放入bf中bf.put(str.getBytes());bf.flip();// 將bf數(shù)據(jù)寫入到fileChannelfileChannel.write(bf);fos.close();} }從本地文件讀數(shù)據(jù)
import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;public class NIOFileChannel02 {public static void main(String[] args) throws Exception{ // 創(chuàng)建一個輸出流FileInputStream fis = new FileInputStream("C:\\Users\\haha\\Desktop\\2.txt");// 通過FileOutputStream 獲取對應的 FileChannel// 這個fileChannel的真是類型是FileChannelImplFileChannel fileChannel = fis.getChannel();// 創(chuàng)建一個緩沖區(qū) ByteBufferByteBuffer bf = ByteBuffer.allocate(1024);// 將str放入bf中fileChannel.read(bf);System.out.println(new String(bf.array()));fis.close();} }Buffer類相關方法
ByteBuffer類(最常用的Buffer類)
NIO還支持通過多個Buffer(即Buffer數(shù)組)完成讀寫操作, 即Scattering 和 Gathering
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel;/** Scattering: 將數(shù)據(jù)寫入到buffer時,可以采用buffer數(shù)組,依次寫入* Gathering: 從buffer讀取數(shù)據(jù)時,可以采用buffer數(shù)組,依次讀*/ public class ScatteringAndGatheringTest {public static void main(String[] args) throws Exception{// 使用ServerSocketChannel,ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);// 綁定端口到socket,并啟動serverSocketChannel.socket().bind(inetSocketAddress);// 創(chuàng)建buffer數(shù)組ByteBuffer[] byteBuffers = new ByteBuffer[2];byteBuffers[0] = ByteBuffer.allocate(5);byteBuffers[1] = ByteBuffer.allocate(3);// 等待客戶端連接SocketChannel socketChannel = serverSocketChannel.accept();int messageLength = 8;// 循環(huán)的讀取while(true){int byteRead = 0;while(byteRead < messageLength){long l = socketChannel.read(byteBuffers);byteRead += l; // 累計讀取的字節(jié)數(shù)System.out.println("byteRead=" + byteRead);// 看看當前buffer的position,limitfor(int i=0; i<byteBuffers.length; i++){System.out.println("position="+byteBuffers[i].position()+" "+"limit="+byteBuffers[i].limit());}}// 將所有buffer進行flipfor(int i=0; i<byteBuffers.length; i++){byteBuffers[i].flip();}// 將數(shù)據(jù)顯示到客戶端long byteWrite = 0;while(byteWrite < messageLength){long l = socketChannel.write(byteBuffers);byteWrite += l;}// 將所有buffer進行clearfor(int i=0; i<byteBuffers.length; i++){byteBuffers[i].clear();}System.out.println("byteRead="+byteRead+" byteWrite="+byteWrite);}} } 《新程序員》:云原生和全面數(shù)字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的netty:IO模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程:线程的状态
- 下一篇: netty:NIO模型--选择器(Sel