文章目录
概念
JDK1.4之后引入了新的IO类库,可以以通道的形式去操作数据;NIO主要有三大核心部分:Channel(通道),Buffer(缓冲区), Selector。传统IO基于字节流和字符流进行操作,而NIO基于Channel和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择区)用于监听多个通道的事件(比如:连接打开,数据到达)。因此,单个线程可以监听多个数据通道。
NIO和传统IO(一下简称IO)之间第一个最大的区别是,IO是面向流的,NIO是面向缓冲区的。 Java IO面向流意味着每次从流中读一个或多个字节,直至读取所有字节,它们没有被缓存在任何地方。此外,它不能前后移动流中的数据。如果需要前后移动从流中读取的数据,需要先将它缓存到一个缓冲区。NIO的缓冲导向方法略有不同。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动。这就增加了处理过程中的灵活性。但是,还需要检查是否该缓冲区中包含所有您需要处理的数据。而且,需确保当更多的数据读入缓冲区时,不要覆盖缓冲区里尚未处理的数据。
IO的各种流是阻塞的。这意味着,当一个线程调用read() 或 write()时,该线程被阻塞,直到有一些数据被读取,或数据完全写入。该线程在此期间不能再干任何事情了。 NIO的非阻塞模式,使一个线程从某通道发送请求读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取。而不是保持线程阻塞,所以直至数据变得可以读取之前,该线程可以继续做其他的事情。 非阻塞写也是如此。一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情。 线程通常将非阻塞IO的空闲时间用于在其它通道上执行IO操作,所以一个单独的线程现在可以管理多个输入和输出通道(channel)。
NIO中channel的主要实现有FileChannel,DatagramChannel,SocketChannel,ServerSocketChannel,分别可以对应文件IO、UDP和TCP(Server和Client),其中FileChannel被修改的类有FileInputStream和FileOutputStream、RandomAccessFile类,都属于字节操作流,与底层的nio性质一致;Reader和Writer这种字符流不能用于产生通道,但是Channels类提供了实用方法,用以在通道中产生Reader和Writer.
Buffer与Selector
NIO中的关键Buffer实现有:ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer,分别对应基本数据类型: byte, char, double, float, int, long, short。当然NIO中还有MappedByteBuffer, HeapByteBuffer, DirectByteBuffer等。
Selector运行单线程处理多个Channel,如果你的应用打开了多个通道,但每个连接的流量都很低,使用Selector就会很方便。例如在一个聊天服务器中。要使用Selector, 得向Selector注册Channel,然后调用它的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新的连接进来、数据接收等。
FileChannel类
常用方法:
//为ByteBuffer分配内存,参数为内存大小,字节数
public static ByteBuffer allocate(int var0)
//分配一个新的直接字节缓冲区
public static ByteBuffer allocateDirect(int var0)
//返回支持此缓冲区的字节数组
public final byte[] array()
基本的读写实例:
@Test
public void readData() throws Exception {
FileInputStream input = new FileInputStream("E:\\file\\test.txt");
FileChannel channel = input.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(8);
while(channel.read(buffer) > -1){
buffer.flip();
while(buffer.hasRemaining())
{
System.out.print((char)buffer.get());
}
buffer.compact();
}
}
@Test
public void writeData() throws Exception {
FileOutputStream input = new FileOutputStream("E:\\file\\test.txt");
FileChannel channel = input.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("szz4".getBytes());
buffer.flip();
channel.write(buffer);
}
SocketChannel与ServerSocketChannel类
NIO强大在非阻塞特性,套接字的某些操作可能会无限期的阻塞,accept()方法可能会一直等待客户端的连接,知道客户端传来新的数据。NIO的channel抽象的一个重要特征就是可以通过配置阻塞特征控制阻塞行为(channel.configureBlocking(false)),实现非阻塞信道;
Selector类可以用于避免使用阻塞式客户端中很浪费资源的“忙等”方法。例如,考虑一个IM服务器。像QQ或者旺旺这样的,可能有几万甚至几千万个客户端同时连接到了服务器,但在任何时刻都只是非常少量的消息。
需要读取和分发。这就需要一种方法阻塞等待,直到至少有一个信道可以进行I/O操作,并指出是哪个信道。NIO的选择器就实现了这样的功能。一个Selector实例可以同时检查一组信道的I/O状态。用专业术语来说,选择器就是一个多路开关选择器,因为一个选择器能够管理多个信道上的I/O操作。然而如果用传统的方式来处理这么多客户端,使用的方法是循环地一个一个地去检查所有的客户端是否有I/O操作,如果当前客户端有I/O操作,则可能把当前客户端扔给一个线程池去处理,如果没有I/O操作则进行下一个轮询,当所有的客户端都轮询过了又接着从头开始轮询;这种方法是非常笨而且也非常浪费资源,因为大部分客户端是没有I/O操作,我们也要去检查;而Selector就不一样了,它在内部可以同时管理多个I/O,当一个信道有I/O操作的时候,他会通知Selector,Selector就是记住这个信道有I/O操作,并且知道是何种I/O操作,是读呢?是写呢?还是接受新的连接;所以如果使用Selector,它返回的结果只有两种结果,一种是0,即在你调用的时刻没有任何客户端需要I/O操作,另一种结果是一组需要I/O操作的客户端,这时你就根本不需要再检查了,因为它返回给你的肯定是你想要的。这样一种通知的方式比那种主动轮询的方式要高效得多!
要使用选择器(Selector),需要创建一个Selector实例(使用静态工厂方法open())并将其注册(register)到想要监控的信道上(注意,这要通过channel的方法实现,而不是使用selector的方法)。最后,调用选择器的select()方法。该方法会阻塞等待,直到有一个或更多的信道准备好了I/O操作或等待超时。select()方法将返回可进行I/O操作的信道数量。现在,在一个单独的线程中,通过调用select()方法就能检查多个信道是否准备好进行I/O操作。如果经过一段时间后仍然没有信道准备好,select()方法就会返回0,并允许程序继续执行其他任务。
示例代码:
private static final Logger log = LoggerFactory.getLogger(SocketChannelTest.class);
@Test
public void clientTest() throws Exception{
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("127.0.0.1", 8000));
if(channel.finishConnect()){
int i = 0;
while(true){
TimeUnit.SECONDS.sleep(1);
buffer.clear();
i++;
String str = "第" + i + "次发送消息";
buffer.put(str.getBytes());
buffer.flip();
while (buffer.hasRemaining()){
channel.write(buffer);
}
buffer.clear();
channel.read(buffer);
buffer.flip();
byte[] bytes = new byte[1024];
buffer.get(bytes, buffer.position(), buffer.limit());
System.out.println(new String(bytes));
}
}
}
@Test
public void serveTest() throws Exception {
ServerSocketChannel channel = ServerSocketChannel.open();
Selector selector = Selector.open();
channel.socket().bind(new InetSocketAddress(8000));
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_ACCEPT);
while (true){
int i = selector.select(3000);
if(i == 0){
log.info("==" + i);
continue;
}
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey key = iterator.next();
iterator.remove();
if(key.isAcceptable()){
handleAccept(key);
}
if(key.isReadable()){
handleRead(key);
}
if(key.isWritable() && key.isValid()){
handleWrite(key);
}
if(key.isConnectable()){
log.info("isConnectable is true");
}
}
}
}
public static void handleAccept(SelectionKey key) throws Exception {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = channel.accept();
if(socketChannel == null){
return;
}
socketChannel.configureBlocking(false);
socketChannel.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocateDirect(1024));
}
public static void handleRead(SelectionKey key) throws Exception {
SocketChannel channel = (SocketChannel) key.channel();
//ByteBuffer buffer = (ByteBuffer) key.attachment();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int i;
while ((i = channel.read(buffer)) > 0){
buffer.flip();
System.out.println(new String(buffer.array()));
buffer.clear();
}
if(i == -1){
channel.close();
}
}
public static void handleWrite(SelectionKey key) throws Exception {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = (ByteBuffer) key.attachment();
buffer.flip();
while (buffer.hasRemaining()){
channel.write(buffer);
}
buffer.compact();
}
MappedByteBuffer类
它使用direct buffer的方式读写文件内容,这种方式的学名叫做内存映射。这种方式直接调用系统底层的缓存,没有JVM和系统之间的复制操作,所以效率大大的提高了。而且由于它这么快,还可以用它来在进程(或线程)间传递消息,基本上能达到和“共享内存页”相同的作用,只不过它是依托实体文件来运行的。
而且它还有另一种能力。就是它可以让我们读写那些因为太大而不能放进内存中的文件。有了它,我们就可以假定整个文件都放在内存中(实际上,大文件放在内存和虚拟内存中),基本上都可以将它当作一个特别大的数组来访问,这样极大的简化了对于大文件的修改等操作。
FileChannel提供了map方法来把文件映射为MappedByteBuffer: MappedByteBuffer map(int mode,long position,long size); 可以把文件的从position开始的size大小的区域映射为MappedByteBuffer,mode指出了可访问该内存映像文件的方式,共有三种,分别为:
MapMode.READ_ONLY(只读): 试图修改得到的缓冲区将导致抛出 ReadOnlyBufferException。
MapMode.READ_WRITE(读/写): 对得到的缓冲区的更改最终将写入文件;但该更改对映射到同一文件的其他程序不一定是可见的(无处不在的“一致性问题”又出现了)。
MapMode.PRIVATE(专用): 可读可写,但是修改的内容不会写入文件,只是buffer自身的改变,这种能力称之为”copy on write”
方法:
//将此缓冲区的内容加载到物理内存中。
public final MappedByteBuffer load()
//告诉这个缓冲区的内容是否驻留在物理内存中。
public final boolean isLoaded()
//强制将此缓冲区内容的任何更改写入包含映射文件的存储设备。
public final MappedByteBuffer force()
代码实例:
@Test
public void readFile() throws Exception {
RandomAccessFile file = new RandomAccessFile("D:\\nginx-1.16.1.zip", "rw");
RandomAccessFile wfile = new RandomAccessFile("D:\\nginx-1.16.1_copy.zip", "rw");
FileChannel channel = file.getChannel();
FileChannel wchannel = wfile.getChannel();
long startTime = System.currentTimeMillis();
MappedByteBuffer mappedBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, file.length());
MappedByteBuffer wmappedBuffer = wchannel.map(FileChannel.MapMode.READ_WRITE, 0, file.length());
while (mappedBuffer.hasRemaining()){
wmappedBuffer.put(mappedBuffer.get());
}
long endTime = System.currentTimeMillis();
log.info("所费时间:" + (endTime - startTime));
}
DatagramChannel类
java NIO中的DatagramChannel定义在java.nio.channels包中,是一个能收发UDP包的通道。因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入。它发送和接收的是数据包。
简单代码实例:
@Test
public void reveive(){
DatagramChannel channel = null;
try{
channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(8888));
ByteBuffer buf = ByteBuffer.allocate(1024);
while(true){
buf.clear();
channel.receive(buf);
buf.flip();
while(buf.hasRemaining()){
System.out.print((char)buf.get());
}
System.out.println();
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
@Test
public void send(){
DatagramChannel channel = null;
try{
channel = DatagramChannel.open();
String info = "I'm the Sender!";
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
buf.put(info.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("127.0.0.1",8888));
System.out.println(bytesSent);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(channel!=null){
channel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
使用selector选择器实例:
private static int port = 8888;
@Test
public void serverTest() throws Exception {
DatagramChannel channel = DatagramChannel.open();
Selector selector = Selector.open();
channel.configureBlocking(false);
channel.socket().bind(new InetSocketAddress(DatagramChannelTest.port));
channel.register(selector, SelectionKey.OP_READ);
while(selector.select() > 0){
Iterator iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey key = (SelectionKey)iterator.next();
iterator.remove();
if(key.isReadable()){
receive(key);
}
}
}
}
@Test
public void clientTest() throws Exception {
DatagramChannel channel = DatagramChannel.open();
Selector selector = Selector.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("127.0.0.1", DatagramChannelTest.port));
channel.write(ByteBuffer.wrap("请求消息".getBytes()));
channel.register(selector, SelectionKey.OP_READ);
while(selector.select() > 0){
Iterator iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if(key.isReadable()){
clientReceive(key);
}
}
}
}
public void receive(SelectionKey key) throws Exception {
if(key == null) {
return;
}
DatagramChannel channel = (DatagramChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
SocketAddress address = channel.receive(buffer);
String clientAddress = address.toString().replace("/", "").split(":")[0];
String clientPort = address.toString().replace("/", "").split(":")[1];
buffer.flip();
String content = "";
while(buffer.hasRemaining()){
buffer.get(new byte[buffer.limit()]);
content += new String(buffer.array());
}
buffer.clear();
System.out.println("接收内容:" + content.trim());
ByteBuffer buffer1 = ByteBuffer.allocate(1024);
buffer1.clear();
buffer1.put(("已收到内容:" + content.trim()).getBytes());
buffer1.flip();
channel.send(buffer1, new InetSocketAddress(clientAddress, Integer.parseInt(clientPort)));
}
public void clientReceive(SelectionKey key) throws Exception {
if(key == null) {
return;
}
DatagramChannel channel = (DatagramChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
channel.receive(buffer);
buffer.flip();
String content = "";
while(buffer.hasRemaining()){
buffer.get(new byte[buffer.limit()]);
content += new String(buffer.array());
}
buffer.clear();
System.out.println("接收内容:" + content.trim());
}