Java NIO是一種基于通道和緩沖區的I/O方式,已經被廣泛的應用,成為解決高并發與大量連接和I/O處理問題的有效方式,
Java NIO相關組件
Java NIO主要有三個核心部分組成,分別是:Channel(通道),Buffer(緩沖區), Selector(選擇器)
- Channel
Channel是所有訪問IO設備的統稱,型別與IO中的Stream,而通道是雙向的,既可以讀又可以寫,但是Stream是單項的,常用的通道有:SocketChannel和ServerSocketChannel(對應TCP的客戶端和服務器端)、FileChannel(對應檔案IO)、DatagramChannel(對應UDP)等
- Buffer
所有資料的讀寫都要經過Buffer,Buffer直接和Channel打交道,是一個存盤資料的容器,通過呼叫Channel.write方法將資料寫入Buffer,Channel.read方法將資料從Buffer中讀取出來,常用的Buffer有:ByteBuffer、LongBuffer、IntBuffer、StringCharBuffer等
- Selector
Selector用來監聽多個Channel的事件(比如:Read、Write、Connect和Accept等),通過單個執行緒輪詢的方式實作了對多個Channel的監聽,
Java IO與NIO的區別
NIO是一種叫非阻塞IO(Non-blocking I/O),基于I/O多路復用來實作的(可參考:I/O模型、select、poll和epoll之間的區別),NIO與之前傳統的I/O模型有很大的不同,具體表現在以下幾個方面:
- 面向流與面向緩沖
Java IO和NIO之間一個最大的區別是,IO是面向流的,NIO是面向緩沖區的,Java IO每次從資料流中讀一個或多個位元組,直至讀取所有位元組,資料流是一次性的,讀取完以后,不能前后移動流中的資料,Java NIO是將資料讀取到緩沖區,可以通過position來回移動訪問緩沖區中的資料,
- 阻塞與非阻塞IO
Java IO中呼叫read和write方法的執行緒會被阻塞的,直到資料全部讀入或者全部寫入完為止,而在Java NIO中,如果需要讀寫資料只用和緩沖區打交道,將資料從緩沖區讀取或者寫入緩沖區以后,執行緒可以繼續做其他事情,不會被block住,
- 選擇器(Selector)
Selector是基于I/O多路復用的機制實作的,將多個Channel注冊到一個Selector上,Selector通過輪詢監聽所有注冊的通道上是否有SelectionKey發生,如果發生了,然后將SelectionKey分派給其他執行緒處理,
Java NIO的應用
通過Java NIO技術簡單實作了一個服務端與客戶端通信的case,具體功能如下:
- 服務端可以向客戶端廣播訊息
- 服務端將一個客戶端的訊息轉發給其他客戶端
- 客戶端向服務端發送訊息
- 客戶端接收服務端的訊息
服務端代碼如下:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
public static void main(String[] args) throws IOException {
new Server().start(); // 啟動服務端程式
}
public Server() throws IOException {
this.init(); // 初始化服務端資料
}
/**
* 服務端埠
*/
private int port = 9999;
/**
* 服務端的Selector用來監聽Channel的事件.
*/
private Selector selector;
/**
* 字符資料編碼
*/
private Charset charset = Charset.forName("UTF-8");
/**
* 讀快取,分配1024Byte的空間
*/
private ByteBuffer readBuffer = ByteBuffer.allocate(1024);
/**
* 寫快取,分配1024Byte的空間
*/
private ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
/**
* 存盤所有客戶端的Channel,轉發的時候使用
*/
private Map<String, Channel> clientSocketChannels = new HashMap<>();
/**
* 定義了一個執行緒池,服務端用來發送資料給客戶端
*/
private static ExecutorService executorService = Executors.newFixedThreadPool(1, runnable -> {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
thread.setName("server-sender");
return thread;
});
/**
* 初始化Channel.
*/
private void init() throws IOException {
// 宣告一個服務端的ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 將服務端的ServerSocketChannel設定成非阻塞模式
serverSocketChannel.configureBlocking(false);
// 設定服務端的socket
ServerSocket serverSocket = serverSocketChannel.socket();
serverSocket.bind(new InetSocketAddress(this.port));
// 宣告一個Selector,用來監聽服務端的所有Channel
this.selector = Selector.open();
// 在ServerSocketChannel上注冊Accept事件,用來接收客戶端的連接
serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
System.out.println("Server is started, the port is " + this.port);
}
/**
* 處理服務端監聽到的事件
*/
private void work(SelectionKey selectionKey) throws IOException {
// 客戶端有Socket連接請求
if (selectionKey.isAcceptable()) {
// 從SelectionKey中獲取服務端的ServerSocketChannel,SelectionKey中包含了服務端與客戶端的所有資訊
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
// 服務端打開一個新的SocketChannel用來與客戶端的SocketChannel進行通信,服務端同時會隨機分配一個埠
SocketChannel socketChannel = serverSocketChannel.accept();
// 將SocketChannel設定成非阻塞模式
socketChannel.configureBlocking(false);
// 將SocketChannel中的Read事件注冊到Selector上
socketChannel.register(this.selector, SelectionKey.OP_READ);
// 存盤服務端為客戶端創建的SocketChannel,為后面的轉發訊息服務
this.clientSocketChannels.put(this.getClientName(socketChannel), socketChannel);
// 通過System.in IO流來創建Scanner
Scanner scanner = new Scanner(System.in);
// 收集服務端控制臺輸入的資料,通過執行緒池將資料廣播給所有客戶端SocketChannel
this.executorService.submit(() -> {
while (true) {
// 該方法會被block住,一直等到服務端控制臺有資料輸入完為止
String sendText = scanner.nextLine();
// 將服務端的資料廣播給所有客戶端
transferToOthers(sendText, null);
}
});
// 服務端監聽到有資料可以讀取,主要是來源于客戶端發送的資料
} else if (selectionKey.isReadable()) {
// 獲取服務端的SocketChannel,然后與客戶端進行通信
// 需要注意的是:當前獲取的SocketChannel與ServerSocketChannel是不同的,
// 這個SocketChannel是通過呼叫ServerSocketChannel.accept方法創建的(存盤在clientSocketChannels集合中)
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
// 清空當前的用來存盤讀資料的buffer
readBuffer.clear();
// 將資料從SocketChannel讀入buffer
int bytes = socketChannel.read(readBuffer);
if (bytes > 0) {
// 使得buffer中的資料可讀
readBuffer.flip();
// 讀取buffer中的資料
String text = String.valueOf(this.charset.decode(readBuffer));
System.out.println(this.getClientName(socketChannel) + ": " + text);
// 將客戶端發送過來的資料轉發給其他客戶端
this.transferToOthers(text, socketChannel);
}
}
}
/**
* 將資料發送給其他客戶端
*/
private void transferToOthers(String text, final SocketChannel socketChannel) {
this.clientSocketChannels.forEach((channelName, channel) -> {
// 獲取之前存盤的與服務端建立連接的客戶端
SocketChannel otherSocketChannel = (SocketChannel) channel;
if (!otherSocketChannel.equals(socketChannel)) {
// 清空寫快取
this.writeBuffer.clear();
// 將資料寫入快取
this.writeBuffer.put(this.charset.encode(this.getClientName(socketChannel) + ": " + text));
// 使得快取中的資料變得可用
this.writeBuffer.flip();
try {
// 將buffer中的資料寫入到其它客戶端
otherSocketChannel.write(this.writeBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
/**
* 通過SocketChannel生成客戶端的名字,用來標識
*/
private String getClientName(SocketChannel socketChannel) {
if (socketChannel == null)
return "[server]";
Socket socket = socketChannel.socket();
return "[" + socket.getInetAddress().toString().substring(1) + ":" + socket.getPort() + "]";
}
/**
* 啟動服務端程式
*/
public void start() {
// 無限回圈來輪詢所有注冊的Channel
while (true) {
try {
// 選擇已經準備好的Channel,該方法是會block住的,直到有事件到達
this.selector.select();
// 獲取所有監聽到的事件
Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
while (iterator.hasNext()) {
// 找到事件SelectionKey,里面包含了事件相關的所有資料
SelectionKey selectionKey = iterator.next();
// 如果事件是有效的
if (selectionKey.isValid()) {
// 處理事件
this.work(selectionKey);
}
// 洗掉已經處理過的事件
iterator.remove();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客戶端代碼如下:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class Client {
public static void main(String[] args) throws IOException {
new Client().start(); // 客戶端程式執行入口
}
/**
* 注冊監聽的服務的埠,并初始化
*/
public Client() throws IOException {
this.serverSocketAddress = new InetSocketAddress("127.0.0.1", 9999);
this.init();
}
/**
* 服務的Socket地址
*/
private SocketAddress serverSocketAddress;
/**
* 客戶端Selector
*/
private Selector selector;
/**
* 字符編碼
*/
private Charset charset = Charset.forName("UTF-8");
/**
* 讀緩沖區
*/
private ByteBuffer readBuffer = ByteBuffer.allocate(1024);
/**
* 寫緩沖區
*/
private ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
/**
* 執行緒池執行客戶端發送資料
*/
private static ExecutorService executorService = Executors.newFixedThreadPool(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
thread.setName("client-sender");
return thread;
}
});
/**
* 初始化客戶端資訊
*/
private void init() throws IOException {
// 宣告一個客戶端SocketChannel
SocketChannel socketChannel = SocketChannel.open();
// 設定成非阻塞模式
socketChannel.configureBlocking(false);
// 宣告一個Selector
this.selector = Selector.open();
// 將客戶端的SocketChannel的連接事件注冊到selector上
socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
// 連接服務端
socketChannel.connect(this.serverSocketAddress);
}
/**
* 處理客戶端資料
*/
private void work(SelectionKey selectionKey) {
try {
// 與服務端建立連接
if (selectionKey.isConnectable()) {
// 從SelectionKey中獲取客戶端的ServerSocketChannel
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
// 判斷連接是否完成
if (socketChannel.isConnectionPending()) {
// 完成連接
socketChannel.finishConnect();
System.out.println("The connection is successful!");
// 通過System.in IO流來創建Scanner
Scanner scanner = new Scanner(System.in);
// 使用執行緒池來完成對客戶端的控制臺資料輸入的監聽
executorService.submit((Runnable) () -> {
while (true) {
try {
// 清空寫緩沖區
writeBuffer.clear();
// 該方法會被block住,一直等到客戶端控制臺有資料輸入完為止
String sendText = scanner.nextLine();
// 將資料寫入寫緩沖區
writeBuffer.put(charset.encode(sendText));
// 使得寫緩沖區中的資料可讀
writeBuffer.flip();
// 將資料通過SocketChannel發送到服務端
socketChannel.write(writeBuffer);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
// 注冊可讀事件,應該當前的SocketChannel與服務端建立連接以后,不需要再監聽創建連接的事件
// 為了復用SocketChannel,將SocketChannel的Read事件注冊到Selector
socketChannel.register(selector, SelectionKey.OP_READ);
}
// 可讀事件,有從服務器端發送過來的資訊,讀取輸出到控制臺上
else if (selectionKey.isReadable()) {
// 獲取與服務端通信的客戶端SocketChannel
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
// 清空讀緩沖區
this.readBuffer.clear();
// 將資料讀取到讀緩沖區,并將資料輸出到客戶端控制臺
int count = socketChannel.read(this.readBuffer);
if (count > 0) {
String text = new String(this.readBuffer.array(), 0, count);
System.out.println(text);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 啟動客戶端程式
*/
public void start() throws IOException {
// 無限回圈,輪詢所有監聽的SocketChannel
while (true) {
// 選擇已經準備好的Channel,該方法是會block住的,直到有事件到達
int events = this.selector.select();
if (events > 0) {
// 找到事件SelectionKey,里面包含了事件相關的所有資料
Set<SelectionKey> selectionKeys = selector.selectedKeys();
// 處理事件
selectionKeys.forEach(selectionKey -> this.work(selectionKey));
// 清空已處理的事件
selectionKeys.clear();
}
}
}
}
總結
- 服務端的
ServerSocketChannel是用來監聽客戶端的連接請求,只有1個且埠固定,主要監聽accept事件 - 服務端的
SocketChannel是用來和客戶端建立資料讀寫操作通信,數量與客戶端的連接數量一致,每個都分配一個隨機的埠,主要監聽read事件 - 每個客戶端有一個
SocketChannel,用來和服務端進行通信,主要監聽connect事件和read事件,connect事件只會在第一連接時發生,read事件是在每次接收服務端資料時發生 - 服務端和客戶端各有一個
Selector,用來監聽所有的SocketChannel或者ServerSocketChannel中注冊的事件,在沒有事件發生的時候,Selector.select()會被block住 - 在定義緩沖區的時候要注意緩沖區的大小,如果太小會報
BufferOverflowException
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/137666.html
標籤:Java
上一篇:深入理解ThreadLocal
下一篇:回圈結構
