IO概念
BIO (Blocking I/O):
同步阻塞 I/O 模式,数据的读取写入必须阻塞在一个线程内等待其完成。在客户端连接数量不高的情况下,是没问题的。但是,当面对十万甚至百万级连接的时候,传统的 BIO 模型是无能为力的。因此,我们需要一种更高效的 I/O 处理模型来应对更高的并发量。
NIO (Non-blocking/New I/O):
NIO 是一种同步非阻塞的 I/O 模型,于 Java 1.4 中引入,对应 java.nio包,提供了 Channel , Selector,Buffer 等抽象。NIO 中的 N 可以理解为 Non-blocking,不单纯是 New。它支持面向缓冲的,基于通道的 I/O 操作方法。 NIO 提供了与传统 BIO 模型中的 Socket 和 ServerSocket 相对应的 SocketChannel 和 ServerSocketChannel 两种不同的套接字通道实现,两种通道都支持阻塞和非阻塞两种模式。对于高负载、高并发的(网络)应用,应使用 NIO 的非阻塞模式来开发
AIO (Asynchronous I/O):
AIO 也就是 NIO 2。在 Java 7 中引入了 NIO 的改进版 NIO 2,它是异步非阻塞的 IO 模型。异步 IO 是基于事件和回调机制实现的,也就是应用操作之后会直接返回,不会堵塞在那里,当后台处理完成,操作系统会通知相应的线程进行后续的操作。AIO 是异步 IO 的缩写,虽然 NIO 在网络操作中,提供了非阻塞的方法,但是 NIO 的 IO 行为还是同步的。对于 NIO 来说,我们的业务线程是在 IO 操作准备好时,得到通知,接着就由这个线程自行进行 IO 操作,IO 操作本身是同步的。目前来说 AIO 的应用还不是很广泛。
文件NIO
/**
*使用NIO向文件中写内容
*/
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("test.txt")) {
//获取该文件输出流的通道
FileChannel channel = fos.getChannel();
//分配buff大小
ByteBuffer buffer = ByteBuffer.allocate(1024);
String str = "hello nio";
//把数据put进buffer
buffer.put(str.getBytes(StandardCharsets.UTF_8));
//buffer指针指向初始位置,不然就会指向str的最后位置的下一个index
buffer.flip();
//channel中写入buffer数据
channel.write(buffer);
} catch (IOException e) {
log.error("", e);
}
}
/**
* 使用NIO读取文件内容
*/
public static void main(String[] args) throws IOException {
String path = "test.txt";
File file = new File(path);
try (FileInputStream fis = new FileInputStream(path)) {
FileChannel channel = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
channel.read(buffer);
log.info("content:{}", new String(buffer.array()));
}
}
/**
* 使用NIO实现文件复制
*/
public static void main(String[] args) throws IOException {
//获取输入输出流
try (FileInputStream fis = new FileInputStream("test.txt");
FileOutputStream fos = new FileOutputStream("D:\\demo\\test.txt")) {
//获取流中的通道
FileChannel sourceChannel = fis.getChannel();
FileChannel destChannel = fos.getChannel();
/*
*复制 destChannel.transferFrom(sourceChannel,0,sourceChannel.size());
*/
sourceChannel.transferTo(0, sourceChannel.size(), destChannel);
}
}
网络NIO
服务段编写:
public static void main(String[] args) throws IOException {
//获取服务端channel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//绑定端口
serverSocketChannel.bind(new InetSocketAddress(9999));
//设置非阻塞
serverSocketChannel.configureBlocking(false);
//创建一个selector
Selector selector = Selector.open();
//将server注册到selector中,事件类型为接收
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
//selector监听客户端,0表示目前没有客户端连接服务器
if (selector.select(2_000) == 0) {
System.out.println("do other things!");
continue;
}
//得到selector监听的客户端,并判断事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {//接受事件
System.out.println("OP_ACCEPT");
//服务端接收,获取socketChannel
SocketChannel socketChannel = serverSocketChannel.accept();
//设置非阻塞
socketChannel.configureBlocking(false);
//注册至selector中
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
if (key.isReadable()) {//读取事件,获取客户端数据
System.out.println("OP_READ");
//拿到数据
ByteBuffer buffer = (ByteBuffer) key.attachment();
//获取selectorKey的channel(selector中的信息存在selectorKey中)
SocketChannel socketChannel = (SocketChannel) key.channel();
//读到channel中
socketChannel.read(buffer);
System.out.println(new String(buffer.array()));
}
//处理完成以后,删除当前key
iterator.remove();
}
}
}
客户端编写:
public static void main(String[] args) throws IOException {
//获取socket通道
SocketChannel channel = SocketChannel.open();
//设置非阻塞
channel.configureBlocking(false);
//连接服务器
SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 9999);
if (!channel.connect(socketAddress)) {
while (!channel.finishConnect()) { //非阻塞可进入代码执行
System.out.println("do other things!");
}
}
//数据准备
String msg = "hello,server!";
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
//往通道中写入数据
channel.write(buffer);
System.in.read();//阻塞,防止程序关闭
}