NIO(New I/O)是Java提供的一种非阻塞I/O模型,它在JDK 1.4中引入。与传统的I/O模型相比,NIO提供了更高效、更灵活的I/O操作方式。
传统的I/O模型使用阻塞式I/O,在进行读写操作时会导致线程被阻塞,直到数据准备好或者写入完成。这种模型对于并发处理能力较弱,当有大量连接同时请求时,每个连接都需要一个独立的线程来处理,造成资源浪费和性能下降。
而NIO采用了事件驱动的方式,通过Selector轮询注册的通道,只有在通道真正有读写事件发生时才会进行处理,避免了线程被阻塞的情况,提高了系统的并发处理能力。
NIO的核心组件包括:Channel、Buffer和Selector。
NIO的工作原理如下:
以下是一个简单的NIO服务器示例,用于接收客户端发送的消息并返回相同的消息给客户端:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NIOServer {
public static void main(String[] args) throws IOException {
// 创建ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8888));
serverSocketChannel.configureBlocking(false);
// 创建Selector
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 阻塞等待就绪的Channel
int readyChannels = selector.select();
if (readyChannels == 0) {
continue;
}
// 获取就绪的SelectionKey集合
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
// 接收新的连接
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
// 读取数据
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = socketChannel.read(buffer);
if (bytesRead > 0) {
buffer.flip();
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
String message = new String(data, "UTF-8");
System.out.println("Received message: " + message);
// 返回相同的消息给客户端
ByteBuffer responseBuffer = ByteBuffer.wrap(data);
socketChannel.write(responseBuffer);
} else if (bytesRead < 0) {
// 客户端关闭连接
socketChannel.close();
}
}
// 移除处理过的SelectionKey
keyIterator.remove();
}
}
}
}
NIO是一种非阻塞I/O模型,通过事件驱动和选择器机制实现高效的I/O操作。它具有高并发性、非阻塞式I/O和内存管理优化等优点,但也存在复杂性较高和对编程人员要求较高的缺点。在使用NIO时需要注意合理设置缓冲区大小、正确释放资源和谨慎处理异常情况。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有