網絡編程-NIO

一、NIO網絡模型

Non-Blocking I/O 或 New I/O,開始與JDK1.4
服務於高併發網絡服務器

NIO網絡模型

二、NIO核心類

NIO核心

  • Channel:通道
  • Buffer:緩衝區
  • Selector:選擇器 或者 多路複用器

1.NIO核心類-Channel

特性

  • 雙向性
  • 非阻塞
  • 操作唯一性:基於字節塊操作,只能通過Buffer

實現

  • 文件類:FileChannel
  • UDP類:DatagramChannel
  • TCP類:ServerSocketChannel / SocketChannel

Socket回顧
服務端代碼

/**
*1. 監聽端口
*/
ServerSocket ServerSocket = new ServerSocket(port:8000;
while(true) {
    // 2. 接受請求,建立連接
    Socket socket = serverSocket.accept();
    // 3. 數據交換
    new Thread(new BIOServerHandler(socket)).start();
}
/**
*4. 關閉資源
*/
serverSocket.close();

客戶端代碼

/**
*1. 建立連接
*/
Socket socket = new Socket("127.0.0.1", port:8000);
/**
* 獲取輸入輸出流
*/
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStram();

Channel使用

/**
*代碼片段1: 服務器端通過服務端socket創建channel
*/
ServerSocketChannel ServerSocketChannel = ServerSocketChannel.open();

/**
* 代碼片段2:服務器端綁定端口
*/
ServerSocketChannel.bind(new InetSocketAddress(8000);

/**
* 代碼片段3:服務器端監聽客戶端連接,建立socketChannel連接
*/
SocketChannel socketChannel = serverSocketChannel.accept();

/**
* 代碼片段4:客戶端連接遠程主機及端口
*/
SocketChannel socketChannel = SocketChannel.open(
                            new InetSocketAdress("127.0.0.1", 8000));

2.NIO核心類-Buffer

作用:讀取Channel中的數據
本質:一塊內存區域
Buffer屬性

  1. Capacity:容量
  2. Position:位置
  3. Limit:上限
  4. Mark:標記

Buffer的使用

/**
*初始化長度爲10的byte類型buffer
*/
ByteBuffer.allocate(10);

在這裏插入圖片描述

/**
* 向byteBuffer中寫入三個字節
*/
byteBuffer.put("abc".getBytes(Charset.forName("UTF-8")));

在這裏插入圖片描述

/**
*將byteBuffer從寫模式切換爲讀模式
*/
byteBuffer.flip();

在這裏插入圖片描述

/**
* 從byteBuffer中讀取一個字節
*/
byteBuffer.get();

在這裏插入圖片描述

/**
* 調用mark方法記錄當前position的位置
*/
byteBuffer.mark();

在這裏插入圖片描述

/**
*調用clear方法,將所有的屬性重置
*/
byteBuffer.clear();

在這裏插入圖片描述

3.NIO核心類-Selector

作用:I/O就緒選擇,能夠檢測1到N個通道,並能知道通道是否爲讀寫做好準備的組件,通過它,一個單獨的線程就能管理多個Channel,從而管理多個網絡連接
地位:NIO網絡編程的基礎
Selector使用

/**
* 代碼片段1:創建Selector
*/
Selector selector = Selector.open();

/**
* 代碼片段2:將channel註冊到selector上,監聽讀就緒事件
*/
SelectionKey selectionKey = chennel.register(selector, SelectionKey.OP_READ);

/**
* 代碼片段3:阻塞等待channel有就緒事件發生
*/
int selectNum = selector.select();

/**
* 代碼片段4:獲取發生就緒事件的channel集合
*/
Set<SelectionKey> selectedKeys = selector.selectedKeys();

SelectionKey簡介

  • 四種就緒狀態常量:Connected,Accept,Read , Write
  • 有價值的屬性
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章