Java nio

本文深入探讨了Java NIO的概念、关键组件如Channel和Buffer的使用,以及如何利用非阻塞IO实现高效的数据传输。通过实例展示了如何使用NIO进行文件复制和HTTP请求响应的处理,并介绍了异步IO的核心API和非阻塞IO的工作原理。
本文转载自http://www.iteye.com/topic/834447

1. [b]基本概念[/b]
IO 是主存和外部设备 ( 硬盘、终端和网络等 ) 拷贝数据的过程。 IO 是操作系统的底层功能实现,底层通过 I/O 指令进行完成。
所有语言运行时系统提供执行 I/O 较高级别的工具。 (c 的 printf scanf,java 的面向对象封装 )
2.[b]Java标准io回顾[/b]
Java 标准 IO 类库是 io 面向对象的一种抽象。基于本地方法的底层实现,我们无须关注底层实现。 InputStream\OutputStream( 字节流 ) :一次传送一个字节。 Reader\Writer( 字符流 ) :一次一个字符。
3.[b]nio 简介[/b]
nio 是 java New IO 的简称,在 jdk1.4 里提供的新 api 。 Sun 官方标榜的特性如下:
–为所有的原始类型提供 (Buffer) 缓存支持。
–字符集编码解码解决方案。
–Channel :一个新的原始 I/O 抽象。
–支持锁和内存映射文件的文件访问接口。
–提供多路 (non-bloking) 非阻塞式的高伸缩性网络 I/O 。
4.[b]Buffer&Chanel[/b]
Channel 和 buffer 是 NIO 是两个最基本的数据类型抽象。
Buffer:
–是一块连续的内存块。
–是 NIO 数据读或写的中转地。
Channel:
–数据的源头或者数据的目的地
–用于向 buffer 提供数据或者读取 buffer 数据 ,buffer 对象的唯一接口。
–异步 I/O 支持
下面代码使用nio实现文件的拷贝

package com.ajita;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class CopyFile {
public static void main(String[] args) throws Exception {
String infile = "C:\\log.txt";
String outfile = "D:\\log.txt";
// 获取源文件和目标文件的输入输出流
FileInputStream fin = new FileInputStream(infile);
FileOutputStream fout = new FileOutputStream(outfile);
// 获取输入输出通道
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// clear方法重设缓冲区,使它可以接受读入的数据
buffer.clear();
// 从输入通道中将数据读到缓冲区
int r = fcin.read(buffer);
// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
if (r == -1) {
break;
}
// flip方法让缓冲区可以将新读入的数据写入另一个通道
buffer.flip();
// 从输出通道中将数据写入缓冲区
fcout.write(buffer);
}
}
}


一个 buffer 主要由 position,limit,capacity 三个变量来控制读写的过程。此三个变量的含义见如下表格:
[table]
|参数|写模式|读模式
|position|当前写入的单位数据数量。|当前读取的单位数据位置。
|limit|代表最多能写多少单位数据和容量是一样的。|代表最多能读多少单位数据,和之前写入的单位数据量一致。
|capacity|buffer 容量|buffer 容量
[/table]

Buffer 常见方法:
flip(): 写模式转换成读模式
rewind() :将 position 重置为 0 ,一般用于重复读。
clear() :清空 buffer ,准备再次被写入 (position 变成 0 , limit 变成 capacity) 。
compact(): 将未读取的数据拷贝到 buffer 的头部位。
mark() 、 reset():mark 可以标记一个位置, reset 可以重置到该位置。

Buffer 常见类型: ByteBuffer 、 MappedByteBuffer 、 CharBuffer 、 DoubleBuffer 、 FloatBuffer 、 IntBuffer 、 LongBuffer 、 ShortBuffer 。

channel 常见类型 :FileChannel 、 DatagramChannel(UDP) 、 SocketChannel(TCP) 、 ServerSocketChannel(TCP)
5.[b]nio.charset[/b]
字符编码解码 : 字节码本身只是一些数字,放到正确的上下文中被正确被解析。向 ByteBuffer 中存放数据时需要考虑字符集的编码方式,读取展示 ByteBuffer 数据时涉及对字符集解码。
Java.nio.charset 提供了编码解码一套解决方案。
以我们最常见的 http 请求为例,在请求的时候必须对请求进行正确的编码。在得到响应时必须对响应进行正确的解码。

以下代码向 baidu 发一次请求,并获取结果进行显示。例子演示到了 charset 的使用。

package com.ajita;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class BaiduReader {
private Charset charset = Charset.forName("GBK");// 创建GBK字符集
private SocketChannel channel;

public void readHTMLContent() {
try {
InetSocketAddress socketAddress = new InetSocketAddress(
"www.baidu.com", 80);
// step1:打开连接
channel = SocketChannel.open(socketAddress);
// step2:发送请求,使用GBK编码
channel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n"));
// step3:读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲
while (channel.read(buffer) != -1) {
buffer.flip();// flip方法在读缓冲区字节操作之前调用。
System.out.println(charset.decode(buffer));
// 使用Charset.decode方法将字节转换为字符串
buffer.clear();// 清空缓冲
}
} catch (IOException e) {
System.err.println(e.toString());
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
}
}
}
}

public static void main(String[] args) {
new BaiduReader().readHTMLContent();
}
}


6.[b]非阻塞 IO[/b]
[b]非阻塞的原理[/b]
把整个过程切换成小的任务,通过任务间协作完成。
由一个专门的线程来处理所有的 IO 事件,并负责分发。
事件驱动机制:事件到的时候触发,而不是同步的去监视事件。
线程通讯:线程之间通过 wait,notify 等方式通讯。保证每次上下文切换都是有意义的。减少无谓的进程切换。

[b]异步 IO 核心 API[/b]
Selector
异步 IO 的核心类,它能检测一个或多个通道 (channel) 上的事件,并将事件分发出去。
使用一个 select 线程就能监听多个通道上的事件,并基于事件驱动触发相应的响应。而不需要为每个 channel 去分配一个线程。
SelectionKey
包含了事件的状态信息和时间对应的通道的绑定。
例子 单线程实现监听两个端口。 ( 见 nio.asyn 包下面的例子。)


package com.ajita.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.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

public class OperationServer implements Runnable {
private int port1 = 8090;
private int port2 = 9090;
private Selector selector;
private ServerSocketChannel serverChannel1;
private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
private ServerSocketChannel serverChannel2;
private SocketChannel socketChannel1;
private SocketChannel socketChannel2;
private AddProcessor client1Processor = new AddProcessor();
private MultiProcessor client2Processor = new MultiProcessor();

public OperationServer() {
initSelector();
}

public void run() {
while (true) {
try {
this.selector.select();
Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = (SelectionKey) selectedKeys.next();
selectedKeys.remove();

if (!key.isValid()) {
continue;
}

if (key.isAcceptable()) {
this.accept(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public void accept(SelectionKey key) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key
.channel();
if (serverSocketChannel.equals(serverChannel1)) {
socketChannel1 = serverSocketChannel.accept();
socketChannel1.configureBlocking(false);
socketChannel1.register(this.selector, SelectionKey.OP_READ);
} else {
socketChannel2 = serverSocketChannel.accept();
socketChannel2.configureBlocking(false);
socketChannel2.register(this.selector, SelectionKey.OP_READ);
}

}

public void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();

this.readBuffer.clear();

// Attempt to read off the channel
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
key.cancel();
socketChannel.close();
return;
}

if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
key.channel().close();
key.cancel();
return;
}
String input = new String(readBuffer.array()).trim();
if (socketChannel.equals(socketChannel1)) {
client1Processor.process(input);
} else {
client2Processor.process(input);
}
}

public void write(SelectionKey key) {

}

/**
* 注册事件到selector;
*/
public void initSelector() {
try {
selector = SelectorProvider.provider().openSelector();
this.serverChannel1 = ServerSocketChannel.open();
serverChannel1.configureBlocking(false);
InetSocketAddress isa = new InetSocketAddress("localhost",
this.port1);
serverChannel1.socket().bind(isa);
serverChannel1.register(selector, SelectionKey.OP_ACCEPT);

this.serverChannel2 = ServerSocketChannel.open();
serverChannel2.configureBlocking(false);
InetSocketAddress isa2 = new InetSocketAddress("localhost",
this.port2);
serverChannel2.socket().bind(isa2);
serverChannel2.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
OperationServer server = new OperationServer();
Thread t = new Thread(server);
t.start();
}
}

package com.ajita.nio;

public class AddProcessor {
public void process(String input) {
if (input != null) {
String[] elements = input.split(",");
if (elements.length != 2) {
System.out
.println("sorry, input expression error! right format:A+B");
return;
}
double A = Double.parseDouble(elements[0]);
double B = Double.parseDouble(elements[1]);

System.out.println(A + "+" + B + "=" + (A + B));
} else {
System.out.println("no input");
}

}
}

package com.ajita.nio;

public class MultiProcessor {
public void process(String input) {
if (input != null) {
String[] elements = input.split(",");
if (elements.length != 2) {
System.out
.println("sorry, input expression error! right format:A*B");
return;
}
double A = Double.parseDouble(elements[0]);
double B = Double.parseDouble(elements[1]);

System.out.println(A + "*" + B + "=" + (A * B));
} else {
System.out.println("no input");
}

}
}

package com.ajita.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class OperationClient {
// Charset and decoder for US-ASCII
private static Charset charset = Charset.forName("US-ASCII");

// Direct byte buffer for reading
private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);

// Ask the given host what time it is
//
private static void query(String host, int port) throws IOException {
byte inBuffer[] = new byte[100];
InetSocketAddress isa = new InetSocketAddress(
InetAddress.getByName(host), port);
SocketChannel sc = null;
while (true) {
try {
System.in.read(inBuffer);
sc = SocketChannel.open();
sc.connect(isa);
dbuf.clear();
dbuf.put(inBuffer);
dbuf.flip();
sc.write(dbuf);
dbuf.clear();

} finally {
// Make sure we close the channel (and hence the socket)
if (sc != null)
sc.close();
}
}
}

public static void main(String[] args) throws IOException {
query("localhost", 8090);// A+B
// query("localhost", 9090);//A*B
}
}

11-13
Java NIO(New I/O)是Java 1.4引入的新的I/O API,用于替代标准的Java I/O API。它提供了非阻塞I/O操作,能显著提高程序的性能和可扩展性,尤其适用于处理大量并发连接的场景。 ### 核心组件 - **Channel(通道)**:Channel是对传统I/O中流的模拟,用于在缓冲区和实体(如文件、套接字)之间传输数据。常见的Channel实现有FileChannel、SocketChannel、ServerSocketChannel和DatagramChannel等。例如,FileChannel用于文件读写,SocketChannel用于TCP网络通信。 - **Buffer(缓冲区)**:Buffer是一个用于存储特定基本类型数据的容器。所有的缓冲区都是Buffer抽象类的子类,如ByteBuffer、CharBuffer、IntBuffer等。使用时,数据先被写入Buffer,再从Buffer读取到Channel,反之亦然。 - **Selector(选择器)**:Selector是Java NIO实现非阻塞I/O的关键。它允许一个线程处理多个Channel的I/O事件。通过将多个Channel注册到一个Selector上,Selector可以不断轮询这些Channel,当某个Channel有可用的I/O操作时,就会被Selector选中,从而实现单线程处理多个连接的目的。 - **SelectionKey(选择键)**:SelectionKey用于维护Selector和SelectableChannel的关系,每个Channel注册到Selector时都会产生一个SelectionKey,它聚合了Channel和Selector,有点类似EventKey。通过SelectionKey可以获取对应的Channel和Selector,还可以设置和查询感兴趣的I/O事件类型,如读、写、连接和接受连接事件等 [^1]。 ### 使用指南 #### 1. 使用FileChannel进行文件读写 ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelExample { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("input.txt"); FileOutputStream fos = new FileOutputStream("output.txt"); FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel()) { ByteBuffer buffer = ByteBuffer.allocate(1024); while (inChannel.read(buffer) != -1) { buffer.flip(); // 切换为读模式 outChannel.write(buffer); buffer.clear(); // 清空缓冲区,准备下一次写入 } } catch (IOException e) { e.printStackTrace(); } } } ``` #### 2. 使用Selector实现非阻塞网络编程 ```java 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; import java.util.Set; public class NioServerExample { public static void main(String[] args) { try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); Selector selector = Selector.open()) { serverSocketChannel.socket().bind(new InetSocketAddress(8080)); serverSocketChannel.configureBlocking(false); 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(); 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); System.out.println(new String(data)); } } keyIterator.remove(); } } } catch (IOException e) { e.printStackTrace(); } } } ``` ### 原理 Java NIO的非阻塞I/O原理基于操作系统的I/O多路复用机制。在传统的阻塞I/O模型中,一个线程只能处理一个连接,当线程在等待某个连接的数据时会被阻塞,无法处理其他连接。而在Java NIO中,Selector利用操作系统提供的I/O多路复用功能,如Linux的select、poll和epoll,通过一个线程监控多个Channel的I/O状态。当某个Channel有数据可读或可写时,Selector会感知到并通知应用程序进行相应的处理,从而实现单线程处理多个连接,提高了系统的并发处理能力。 ### 应用场景 - **网络编程**:在构建高性能的网络服务器时,如Web服务器、聊天服务器、游戏服务器等,Java NIO的非阻塞I/O特性可以显著减少线程数量,降低系统资源消耗,提高服务器的并发处理能力。 - **文件处理**:对于大文件的读写操作,使用FileChannel和ByteBuffer可以提高文件读写的效率,尤其是在需要随机访问文件内容时。 - **实时数据处理**:在处理实时数据流时,如视频流、音频流等,Java NIO可以高效地处理数据的传输和处理,确保数据的实时性。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值