什么是Java IO模型?
Java I/O模型是指Java编程语言中用于输入和输出操作的一组API和模型。它提供了一种机制,让程序能够与外部设备(如文件、网络、数据库等)进行数据交换。
Java I/O模型主要涉及两个方面:输入和输出。输入(Input)指从外部设备(如文件、网络)读取数据到程序中,输出(Output)指将程序中的数据写入到外部设备中。
Java提供了多种I/O模型,其中包括传统的阻塞I/O(BIO)、非阻塞I/O(NIO)和异步I/O(AIO)
IO模型特点介绍
同步和异步关注的是程序的执行方式和操作的完成方式。
阻塞和非阻塞关注的是线程是否被暂停执行
阻塞I/O(如InputStream和OutputStream):
特点:
在阻塞I/O模型中,当程序执行I/O操作时,线程会被阻塞,直到操作完成(满足条件)才能继续执行。阻塞I/O是同步的,意味着线程会等待数据准备好或操作完成。
作用:
适用于连接数较少且并发要求不高的情况。在阻塞模式下,线程可以直接从输入流中读取数据或将数据写入输出流。
比如:使用阻塞I/O读取文件内容。当程序执行文件读取操作时,线程会被阻塞,直到文件中的数据被完全读取后才能继续执行。
非阻塞I/O(如SocketChannel和ServerSocketChannel):
特点:
在非阻塞I/O模型中,当程序执行I/O操作时,线程不会被阻塞,可以立即返回(执行其他操作),即使操作未完成,线程可以继续执行其他任务。
作用:
适用于连接数较多且并发要求较高的情况,在非阻塞模式下,程序需要轮询来检查I/O操作是否完成。
比如:使用非阻塞I/O进行网络通信。当程序执行网络读取操作时,如果没有数据可用,线程不会被阻塞,可以继续执行其他任务,然后再次检查是否有数据可用。
同步 I/O(如BufferedReader和BufferedWriter):
特点:
同步I/O是指程序在执行I/O操作时会等待操作完成,并且需要等待操作的结果返回。
作用:
适用于简单的I/O操作,程序需要等待操作完成后才能继续执行后续的逻辑。
比如:使用同步I/O发送HTTP请求。程序发送一个HTTP请求,然后等待服务器返回响应,然后再继续执行后续的逻辑。
异步I/O(如AsynchronousSocketChannel和AsynchronousFileChannel):
特点:
异步I/O是指程序发起I/O操作后不需要等待操作完成,而是通过回调函数等待操作完成的通知。
作用:
适用于需要同时处理多个I/O操作的情况,提高系统的并发性能。
比如:使用异步I/O处理文件读取操作。程序发起读取文件的操作后,可以继续执行其他任务,当文件读取完成后,通过回调函数接收到通知,并处理读取到的数据。
BIO(Blocking I/O)
BIO是传统的同步阻塞式I/O模型。在BIO中,每个I/O操作都是阻塞的,意味着当一个线程执行I/O操作时,它会被阻塞,直到操作完成。
每个连接都会创建一个独立的线程,该线程负责阻塞地接受和处理客户端连接,这就意味着在同一时间只能处理一个连接,当有大量的并发请求时,性能会受到限制。
在Java中使用Socket和ServerSocket类进行实现。
实现一个简单的BIO服务器:
public class BioServer {
public static void main(String[] args) {
try {
//创建服务端对象并监听8080端口
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("BIOServer started on port 8080");
while (true) {
//等待(接收)客户端连接请求,连接期间,accept() 方法会阻塞程序的执行,直到有客户端连接成功
Socket socket = serverSocket.accept();
System.out.println("连接信息: " + socket.getRemoteSocketAddress());
// 处理连接
handleConnection(socket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleConnection(Socket socket) throws IOException {
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
// 读取客户端发送的数据
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer);
String requestData = new String(buffer, 0, bytesRead);
System.out.println("接收的客户端数据: " + requestData);
// 发送响应给客户端
String responseData = "Hello from BIOServer!";
outputStream.write(responseData.getBytes());
outputStream.flush();
// 关闭连接
socket.close();
}
}
NIO(Non-blocking I/O):
NIO是Java 1.4引入的一种非阻塞式I/O模型(可设置同步或异步)。
它通过引入通道(Channel)和缓冲区(Buffer)的概念,可以更灵活地进行数据的读取和写入。
NIO的核心组件包括通道(Channel)、缓冲区(Buffer)和选择器(Selector)。
通道负责与I/O设备进行交互,缓冲区用于存储数据,选择器用于管理多个通道的I/O操作。
NIO提供了更好的性能和可扩展性,适合处理大量连接和高并发的网络应用。
NIO在Java中使用java.nio、java.nio.file和java.nio.channels包中的类进行实现。
实现一个简单的NIO服务器:
public class NioServer {
public static void main(String[] args) {
try {
//创建服务器套接字通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//绑定地址
serverSocketChannel.bind(new InetSocketAddress("192.168.1.100",8080));
//非堵塞模式
serverSocketChannel.configureBlocking(false);
System.out.println("NIO服务 started on port 8080");
//创建选择器
Selector selector = Selector.open();
//注册选择器,监听连接请求事件 OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 选择器进行事件轮询
int readyChannels = selector.select();
if (readyChannels == 0) {
continue;
}
//处理就绪的事件:通过迭代器遍历事件
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
//如果事件是连接请求事件 OP_ACCEPT
if (key.isAcceptable()) {
// 处理连接请求
handleAccept(key);
} else if (key.isReadable()) {
// 处理读取数据
handleRead(key);
}else if (key.isWritable()) {
// 处理写入数据
handleWrite(key);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleAccept(SelectionKey key) throws IOException {
// 获取服务器套接字通道和客户端套接字通道
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
// 注册客户端套接字通道到选择器上,监听读取事件
socketChannel.register(key.selector(), SelectionKey.OP_READ);
System.out.println("连接信息: " + socketChannel.getRemoteAddress());
}
private static void handleRead(SelectionKey key) throws IOException {
// 获取客户端套接字通道和缓冲区
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = socketChannel.read(buffer);
if (bytesRead == -1) {
// 连接已关闭
socketChannel.close();
return;
}
buffer.flip();
byte[] data = new byte[bytesRead];
buffer.get(data);
System.out.println("接收的客户端数据: " + new String(data));
// 发送响应给客户端
String responseData = "Hello from NIOServer!";
ByteBuffer responseBuffer = ByteBuffer.wrap(responseData.getBytes());
socketChannel.write(responseBuffer);
System.out.println("响应数据给客户端");
// 注册写事件,用于写入响应数据
socketChannel.register(key.selector(), SelectionKey.OP_WRITE, responseBuffer);
}
private static void handleWrite(SelectionKey key) throws IOException {
// 获取客户端套接字通道和响应缓冲区
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = (ByteBuffer) key.attachment();
socketChannel.write(buffer);
if (!buffer.hasRemaining()) {
// 写入完成,注册读事件,继续读取客户端数据
socketChannel.register(key.selector(), SelectionKey.OP_READ);
}
}
}
AIO(Asynchronous I/O):
AIO是Java 7引入的新的异步I/O模型,也被称为NIO.2。
在AIO模型中,所有的I/O操作都是异步的,通过回调函数(CompletionHandler)来处理I/O事件。它使用了回调机制,在进行I/O操作时,可以继续执行其他任务而不需要等待操作完成。
当I/O操作完成时,系统会通知应用程序进行处理。这种方式可以提高系统的并发性能,这种模型适合处理连接数较多且每个连接的数据交互较频繁的场景(大量并发连接)。
在Java中使用java.nio.channels和java.util.concurrent包类进行实现。
实现一个简单的AIO服务器:
public class AioServer {
public static void main(String[] args) {
try {
// 打开异步服务器套接字通道
AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
// 绑定服务器套接字通道到指定地址
serverSocketChannel.bind(new InetSocketAddress("192.168.1.100",8080));
System.out.println("AIO服务 started on port 8080");
// 接受客户端连接请求
serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
@Override
public void completed(AsynchronousSocketChannel socketChannel, Void attachment) {
// 处理连接
serverSocketChannel.accept(null, this);
handleConnection(socketChannel);
}
//异步操作失败时被调用的回调方法
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
}
});
// 阻塞主线程,保持服务器运行
Thread.sleep(Integer.MAX_VALUE);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private static void handleConnection(AsynchronousSocketChannel socketChannel) {
//创建缓冲区操作数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.read(buffer, null, new CompletionHandler<Integer, Void>() {
@Override
public void completed(Integer bytesRead, Void attachment) {
if (bytesRead == -1) {
// 连接已关闭
try {
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
buffer.flip();
byte[] data = new byte[bytesRead];
buffer.get(data);
System.out.println("从客户端接收的数据: " + new String(data));
// 发送响应给客户端
String responseData = "Hello from AIOServer!";
ByteBuffer responseBuffer = ByteBuffer.wrap(responseData.getBytes());
socketChannel.write(responseBuffer, null, new CompletionHandler<Integer, Void>() {
@Override
public void completed(Integer bytesWritten, Void attachment) {
if (responseBuffer.hasRemaining()) {
// 写入未完成,继续写入
socketChannel.write(responseBuffer, null, this);
} else {
// 写入完成,继续读取客户端数据
try {
buffer.clear();
socketChannel.read(buffer, null, this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
}
});
}
@Override
public void failed(Throwable exc, Void attachment) {
exc.printStackTrace();
}
});
}
}