Java NIO (New IO)是从Java1.4版本开始引入的一个新的IO API,可以替代次奥准的Java IO API。NIO支持面向缓冲区的,基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。
比较NIO与IO
IO模型 | IO | NIO |
---|---|---|
通信 | 面向流(Stream Oriented) | 面向缓冲区(Buffer Oriented) |
处理 | 阻塞IO(Blocking IO) | 非阻塞IO(Non Blocking IO) |
触发 | (无) | 选择器(Selectors) |
面向流与面向缓冲区的区别以及对通道与缓冲区的理解
面向流是单向的,文件与程序之间建立数据流,输入流和输出流都需要建立不同的“管道”。抽象的理解为自来水管和下水道吧,水就是传输的数据。
面向缓冲区,文件与程序之间建立通道,里面存在缓冲区。抽象的理解可以把通道认为是铁路,缓冲区认为是一辆火车,而载着的货物也就是所要传输的数据了。
简单认为:通道负责传输,缓冲区负责存储。
缓冲区(Buffer)
Buffer在Java NIO 中负责数据的存取,缓冲区就是数组,用于存储不同数据类型的数据。
缓冲区类型
根据数据类型的不同(boolean除外),提供了相应类型的缓冲区。
ByteBuffer
CharBuffer
ShortBuffer
IntBuffer
LongBuffer
FloatBuffer
DoubleBuffer
上述缓冲区的管理方式几乎一致,通过allocate()获取缓冲区。ByteBuffer最为常用。
缓冲区存取数据的两个核心方法
获取 Buffer 中的数据
get() :读取单个字节
get(byte[] dst):批量读取多个字节到 dst 中
get(int index):读取指定索引位置的字节(不会移动 position)
放入数据到 Buffer 中
put(byte b):将给定单个字节写入缓冲区的当前位置
put(byte[] src):将 src 中的字节写入缓冲区的当前位置
put(int index, byte b):将指定字节写入缓冲区的索引位置(不会移动 position)
缓冲区的四个核心属性
①capacity: 容量,表示缓冲区中最大存储数据的容量,一但声明不能改变。(因为底层是数组,数组一但被创建就不能被改变)
②limit: 界限,表示缓冲区中可以操作数据的大小。(limit后数据不能进行读写)
③position: 位置,表示缓冲区中正在操作数据的位置,0<= mark <= position <= limit <= capacity
④mark:标记,表示记录当前position的位置,可以通过reset()恢复到mark的位置。
几个常用方法
①allocate():分配缓冲区:
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
②put():将数据存入缓冲区
String str = "这是一个测试数据";
byteBuffer.put(str.getBytes());
③flip():切换到读取数据的模式
④get():读取数据
byte[] bytes = new byte[byteBuffer.limit()];
byteBuffer.get(bytes);
System.out.println(new String(bytes,0,bytes.length));
⑤rewind():重复读,使position归0
⑥clear():清空缓冲区,缓冲区中的数据还在,只是处于“被遗忘“的状态。只是不知道位置界限等,读取会有困难。
⑦mark():标记。mark会记录当前的position,limit,capacity
⑧reset():position,limit,capacity恢复到mark记录的位置
案例:
package com.hanker.nio1;
import java.nio.ByteBuffer;
public class TestByteBuffer {
public static void main(String[] args) {
//分配直接缓冲区
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
System.out.println("是否直接缓冲区:"+buf.isDirect());
}
private static void test2() {
String str = "abcde";
//1.分配一个指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put(str.getBytes());
buf.flip();
byte[] dst = new byte[buf.limit()];
buf.get(dst, 0, 2);
System.out.println(new String(dst,0,2));
System.out.println(buf.position());
//7. mark():标记
buf.mark();
buf.get(dst, 2, 2);
System.out.println(new String(dst,2,2));
System.out.println(buf.position());
//8.reset():恢复到mark的位置
buf.reset();
System.out.println(buf.position());
//9.是否还有剩余数据
if(buf.hasRemaining()) {
//如果有还剩下多少数据
System.out.println(buf.remaining());
}
}
private static void test1() {
String str = "abcde";
//1.分配一个指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
System.out.println("------------allocate()--------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//2.利用put()存入数据到缓冲区
buf.put(str.getBytes());
System.out.println("------------put()--------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//3.切换读取数据模式
buf.flip();
System.out.println("------------flip()--------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//4.利用get()读取缓冲区中的数据
byte[] dst = new byte[buf.limit()];
buf.get(dst);
System.out.println("读取的数据:"+new String(dst,0,dst.length));
System.out.println("------------get()--------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//5.rewind():可重复读数据
buf.rewind();
System.out.println("------------rewind()--------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//6.clear():清空缓冲区,缓冲区中的数据依然存在,处于被遗忘状态
buf.clear();
System.out.println("------------clear()--------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
System.out.println((char)buf.get());
}
}
直接缓冲区与非直接缓冲区
①字节缓冲区要么是直接的,要么是非直接的。如果为直接字节缓冲区,则 Java 虚拟机会尽最大努力直接在此缓冲区上执行本机 I/O 操作。也就是说,在每次调用基础操作系统的一个本机 I/O 操作之前(或之后),虚拟机都会尽量避免将缓冲区的内容复制到中间缓冲区中(或从中间缓冲区中复制内容)。
②直接字节缓冲区可以通过调用此类的 allocateDirect() 工厂方法来创建。此方法返回的缓冲区进行分配和取消分配所需成本通常高于非直接缓冲区。直接缓冲区的内容可以驻留在常规的垃圾回收堆之外,因此,它们对应用程序的内存需求量造成的影响可能并不明显。所以,建议将直接缓冲区主要分配给那些易受基础系统的本机 I/O 操作影响的大型、持久的缓冲区。一般情况下,最好仅在直接缓冲区能在程序性能方面带来明显好处时分配它们。
③直接字节缓冲区还可以通过 FileChannel 的 map() 方法 将文件区域直接映射到内存中来创建。该方法返回MappedByteBuffer 。Java 平台的实现有助于通过 JNI 从本机代码创建直接字节缓冲区。如果以上这些缓冲区中的某个缓冲区实例指的是不可访问的内存区域,则试图访问该区域不会更改该缓冲区的内容,并且将会在访问期间或稍后的某个时间导致抛出不确定的异常。
④字节缓冲区是直接缓冲区还是非直接缓冲区可通过调用其 isDirect() 方法来确定。提供此方法是为了能够在性能关键型代码中执行显式缓冲区管理。
非直接缓冲区:通过allocate()方法分配缓冲区,将缓冲区建立在JVM的内存中。在每次调用基础操作系统的一个本机IO之前或者之后,虚拟机都会将缓冲区的内容复制到中间缓冲区(或者从中间缓冲区复制内容),缓冲区的内容驻留在JVM内,因此销毁容易,但是占用JVM内存开销,处理过程中有复制操作。
非直接缓冲区的写入步骤:
①创建一个临时的ByteBuffer对象。
②将非直接缓冲区的内容复制到临时缓冲中。
③使用临时缓冲区执行低层次I/O操作。
④临时缓冲区对象离开作用域,并最终成为被回收的无用数据。
直接缓冲区:通过allocateDirect()方法分配直接缓冲区,将缓冲区建立在物理内存中,可以提高效率。
直接缓冲区在JVM内存外开辟内存,在每次调用基础操作系统的一个本机IO之前或者之后,虚拟机都会避免将缓冲区的内容复制到中间缓冲区(或者从中间缓冲区复制内容),缓冲区的内容驻留在物理内存内,会少一次复制过程,如果需要循环使用缓冲区,用直接缓冲区可以很大地提高性能。虽然直接缓冲区使JVM可以进行高效的I/O操作,但它使用的内存是操作系统分配的,绕过了JVM堆栈,建立和销毁比堆栈上的缓冲区要更大的开销.
观察源码
allocate():
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
进入到 HeapByteBuffer()中可以看到:
HeapByteBuffer(int cap, int lim) { // package-private
super(-1, 0, lim, cap, new byte[cap], 0);
/*
hb = new byte[cap];
offset = 0;
*/
}
可以看出直接在堆内存中开辟空间,也就是数组。
allocateDriect():
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
进入到DirectByteBuffer()中可以看到:
DirectByteBuffer(int cap) { // package-private
super(-1, 0, cap, cap);
boolean pa = VM.isDirectMemoryPageAligned();
int ps = Bits.pageSize();
long size = Math.max(1L, (long)cap + (pa ? ps : 0));
Bits.reserveMemory(size, cap);
long base = 0;
try {
base = unsafe.allocateMemory(size);
} catch (OutOfMemoryError x) {
Bits.unreserveMemory(size, cap);
throw x;
}
unsafe.setMemory(base, size, (byte) 0);
if (pa && (base % ps != 0)) {
// Round up to page boundary
address = base + ps - (base & (ps - 1));
} else {
address = base;
}
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
att = null;
}
由 VM.isDirectMemoryPageAligned();可以看出直接调用了内存页,让操作系统开辟缓存空间。
通道
通道(Channel)表示IO源与目标打开的连接。Channel类似于传统的”流“,只不过Channel本身不能直接访问数据,Channel只能与Buffer进行交互。
- Channel是一个独立的处理器,专门用于IO操作,附属于CPU。
- 在提出IO请求的时候,CPU不需要进行干预,也就提高了效率。
作用:用于源节点与目标节点的连接。在Java NIO中负责缓冲区中数据的传输。Channel本身并不存储数据,因此需要配合Buffer一起使用。
主要实现类
java.nio.channels.Channel接口:
用于本地数据传输:FileChannel
用于网络数据传输:SocketChannel/ServerSocketChannel/DatagramChannel
获取通道
①Java 针对支持通道的类提供了一个 getChannel() 方法。本地IO操:FileInputStream/FileOutputStream/RandomAccessFile
网络IO:Socket/ServerSocket/DatagramSocket
②在JDK1.7中的NIO.2 针对各个通道提供了静态方法 open();
③在JDK1.7中的NIO.2 的Files工具类的 newByteChannel();
案例:
package com.hanker.nio1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class TestChannel {
public static void main(String[] args) throws IOException {
String url = "http://henan.163.com/20/0120/08/F3AQO6B404398DMR.html";
//读取web网页
try(FileChannel destChannel =
FileChannel.open(Paths.get("html.txt"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);){
InputStream input = new URL(url).openStream();
ReadableByteChannel srcChannel = Channels.newChannel(input);
destChannel.transferFrom(srcChannel, 0, Integer.MAX_VALUE);
}
}
//通道之间的数据传输(也是利用的直接缓冲器的方式)
private static void test4() throws IOException {
//获取通道对象
FileChannel inChannel = FileChannel.open(Paths.get("1.jpeg"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("4.jpeg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
//inChannel.transferTo(0, inChannel.size(), outChannel);
outChannel.transferFrom(inChannel, 0, inChannel.size());
inChannel.close();
outChannel.close();
}
//内存映射文件-直接缓冲区
private static void test3() throws IOException {
//获取通道对象
FileChannel inChannel = FileChannel.open(Paths.get("1.jpeg"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("3.jpeg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
//内存映射文件
MappedByteBuffer inMappeBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMappeBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
//直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMappeBuf.limit()];
inMappeBuf.get(dst);
outMappeBuf.put(dst);
inChannel.close();
outChannel.close();
}
//利用通道完成文件复制-非直接缓冲区
private static void test2() throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("1.jpeg");
FileOutputStream fos = new FileOutputStream("2.jpeg");
//①获取通道
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
//②分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//③将通道中的数据写入缓冲区
while(inChannel.read(buf) != -1) {
buf.flip();//切换读取数据的模式
outChannel.write(buf);//将缓冲区的数据写入通道中
buf.clear();//清空缓冲区
}
outChannel.close();
inChannel.close();
fos.close();
fis.close();
}
private static void test1() throws IOException {
// 创建FileChannel对象
FileChannel channel = FileChannel.open(Paths.get("my.txt"), StandardOpenOption.CREATE,StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.allocate(64);
buffer.putChar('A').flip();
channel.write(buffer);
}
}
分散(Scatter)与聚集(Gather)
分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中
聚集写入(Gathering Writes):将多个缓冲区中的数据聚集到通道中
分散读取
聚集写入
package com.hanker.nio1;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class TestScatter_Gather {
public static void main(String[] args) throws Exception {
RandomAccessFile raf1 = new RandomAccessFile("my.txt", "rw");
//1.获取通道
FileChannel ch1 = raf1.getChannel();
//2.分配指定大小的缓冲区
ByteBuffer buf1 = ByteBuffer.allocate(100);
ByteBuffer buf2 = ByteBuffer.allocate(1024);
//3.分散读取
ByteBuffer [] bufs = {buf1,buf2};
ch1.read(bufs);
for(ByteBuffer byteBuffer : bufs) {
byteBuffer.flip();
}
System.out.println(new String(bufs[0].array(),0,bufs[0].limit()));
System.out.println("==========");
System.out.println(new String(bufs[1].array(),0,bufs[0].limit()));
//4.聚集写入
RandomAccessFile raf2 = new RandomAccessFile("my2.txt", "rw");
FileChannel ch2 = raf2.getChannel();
ch2.write(bufs);
ch2.close();
ch1.close();
}
}
字符集Charset
设置字符集,解决乱码问题
编码:字符串->字节数组
解码:字节数组->字符串
思路
用Charset.forName(String)构造一个编码器或解码器,利用编码器和解码器来对CharBuffer编码,对ByteBuffer解码。需要注意的是,在对CharBuffer编码之前、对ByteBuffer解码之前,请记得对CharBuffer、ByteBuffer进行flip()切换到读模式如果编码和解码的格式不同,则会出现乱码。
案例:
package com.hanker.nio1;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Map.Entry;
import java.util.SortedMap;
public class TestCharSet {
public static void main(String[] args) throws CharacterCodingException {
Charset charset = Charset.forName("utf-8");
Charset charset1 = Charset.forName("gbk");
// 获取编码器 utf-8
CharsetEncoder encoder = charset1.newEncoder();
// 获得解码器 gbk
CharsetDecoder decoder = charset1.newDecoder();
CharBuffer buffer = CharBuffer.allocate(1024);
buffer.put("绝不敷衍,从不懈怠!");
buffer.flip();
// 编码
ByteBuffer byteBuffer = encoder.encode(buffer);
for (int i = 0; i < 20; i++) {
System.out.println(byteBuffer.get());
}
// 解码
byteBuffer.flip();
CharBuffer charBuffer = decoder.decode(byteBuffer);
System.out.println(charBuffer.toString());
}
//获取系统支持的所有字符集
private static void test1() {
SortedMap<String, Charset> sets = Charset.availableCharsets();
for(Entry<String, Charset> entry :sets.entrySet()) {
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
}
}
在for循环中使用过到了ByteBuffer的get()方法。一开始习惯性的在get()方法里加上了变量i随即出现了问题,无法取得数据。注释代码byteBuffer.flip();之后可以执行。当直接使用get()方法时,不加byteBuffer.flip();则会报错。所以就来区别一下ByteBuffer里的get();与get(int index);的区别。
查看get();方法源码:
/**
* Relative <i>get</i> method. Reads the byte at this buffer's
* current position, and then increments the position.
* @return The byte at the buffer's current position
*
* @throws BufferUnderflowException
* If the buffer's current position is not smaller than its limit
*/
public abstract byte get();
可以看出返回的值是“ The byte at the buffer’s current position”,就是返回缓冲区当前位置的字节。"then increments the position"也说明了返回字节之后,position自动加1,就是指向下一字节。上述情况如果是get(index),则是下面的方法:
/**
* Absolute <i>get</i> method. Reads the byte at the given
* index.
* @param index
* The index from which the byte will be read
*
* @return The byte at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit
*/
public abstract byte get(int index);
- 由“The byte at the given index”可以知道返回的是给定索引处的字节。position并未移动。如果之后再执行flip();操作则读取不到任何数据。原因接着往下看。
- 再来看一看 flip();方法源码:
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
注意:limit=position
,如果使用get(index);的方法,则执行完position = 0,所以limit也会变成0,之后无法读取数据。
网络阻塞IO与非阻塞IO
传统IO是阻塞式的,也就是说,当一个线程调用 read() 或 write()时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此期间不能执行其他任务。因此,在完成网络通信进行 IO 操作时,由于线程会阻塞,所以服务器端必须为每个客户端都提供一个独立的线程进行处理,当服务器端需要处理大量客户端时,性能急剧下降。
NIO是非阻塞式的,当线程从某通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO操作,所以单独的线程可以管理多个输入和输出通道。因此, NIO 可以让服务器端使用一个或有限几个线程来同时处理连接到服务器端的所有客户端。
阻塞模式与非阻塞模式
传统阻塞IO方式:客户端向服务器端发送请求,服务器端便开始监听客户端的数据是否传过来。这时候客户端在准备自己的数据,而服务器端就需要干等着。即使服务器端是多线程的,但有时一味增加线程数,只会让阻塞的线程越来越多。NIO的非阻塞方式:将用于传输的通道全部注册到选择器上。选择器的作用是监控这些通道的IO状况(读,写,连接,接收数据的情况等状况)。
选择器与通道之间的联系:
通道注册到选择器上,选择器监控通道;当某一通道,某一个事件就绪之后,选择器才会将这个通道分配到服务器端的一个或多个线程上,再继续运行。例如客户端需要发送数据给服务器端,只当客户端所有的数据都准备完毕后,选择器才会将这个注册的通道分配到服务器端的一个或多个线程上。在客户端准备数据这段时间,服务器端的线程可以执行别的任务。
选择器( Selector)与SelectableChannle
选择器( Selector) 是 SelectableChannle 对象的多路复用器, Selector 可以同时监控多个 SelectableChannel 的 IO 状况,也就是说,利用 Selector可使一个单独的线程管理多个 Channel。 Selector 是非阻塞 IO 的核心。
SelectableChannle 的结构如下图(注意:FileChannel不是可作为选择器复用的通道!FileChannel不能注册到选择器Selector!FileChannel不能切换到非阻塞模式!FileChannel不是SelectableChannel的子类!)
选择器的使用方法
①创建 Selector :通过调用 Selector.open() 方法创建一个 Selector
②向选择器注册通道: SelectableChannel.register(Selector sel, int ops)
当调用 register(Selector sel, int ops) 将通道注册选择器时,选择器对通道的监听事件,需要通过第二个参数 ops 指定。可以监听的事件类型( 可使用 SelectionKey 的四个常量表示):
读 : SelectionKey.OP_READ ( 1)
写 : SelectionKey.OP_WRITE ( 4)
连接 : SelectionKey.OP_CONNECT ( 8)
接收 : SelectionKey.OP_ACCEPT ( 16)
若注册时不止监听一个事件,则可以使用“位或”操作符连接。
选择键(SelectionKey)
SelectionKey: 表示 SelectableChannel 和 Selector 之间的注册关系。每次向选择器注册通道时就会选择一个事件(选择键)。 选择键包含两个表示为整数值的操作集。操作集的每一位都表示该键的通道所支持的一类可选择操作。
方 法 | 描 述 |
---|---|
int interestOps() | 获取感兴趣事件集合 |
int readyOps() | 获取通道已经准备就绪的操作的集合 |
SelectableChannel channel() | 获取注册通道 |
Selector selector() | 返回选择器 |
boolean isReadable() | 检测 Channal 中读事件是否就绪 |
boolean isWritable() | 检测 Channal 中写事件是否就绪 |
boolean isConnectable() | 检测 Channel 中连接是否就绪 |
boolean isAcceptable() | 检测 Channel 中接收是否就绪 |
Selector常用方法
Set keys() | 所有的 SelectionKey 集合。代表注册在该Selector上的Channel |
---|---|
selectedKeys() | 被选择的 SelectionKey 集合。返回此Selector的已选择键集 |
int select() | 监控所有注册的Channel,当它们中间有需要处理的 IO 操作时, 该方法返回,并将对应得的 SelectionKey 加入被选择的 SelectionKey 集合中,该方法返回这些 Channel 的数量。 |
int select(long timeout) | 可以设置超时时长的 select() 操作 |
int selectNow() | 执行一个立即返回的 select() 操作,该方法不会阻塞线程 |
Selector wakeup() | 使一个还未返回的 select() 方法立即返回 |
void close() | 关闭该选择器 |
使用NIO完成网络通信的三个核心
-
通道(Channel):负责连接
-
缓冲区(Buffer):负责数据的存取
-
选择器(Select):是SelectableChannel的多路复用器。用于监控SelectableChannel的IO状况。
java.mio.channels.Channel 接口: |-- SelectableChannel |--SocketChannel |--ServerSocketChannel |--DatagramChannel |--Pipe.SinkChannel |--Pipe.sourceChannel
阻塞模式完成客户端向服务器端传输数据
//===========服务器端======
package com.hanker.nio1;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class TestServerSocketChannel {
public static void main(String[] args) throws IOException {
//1.获取通道
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(9898));//绑定链接
//2. 创建FileChannel
FileChannel outChannel = FileChannel.open(Paths.get("5.jpeg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//3.获取客户端链接的通道
SocketChannel socketChannel = ssc.accept();
//4.分配指定大小的缓冲区
ByteBuffer dst = ByteBuffer.allocate(1024);
//5.接收数据并保存
while(socketChannel.read(dst) != -1) {
dst.flip();
outChannel.write(dst);
dst.clear();
}
//6.关闭通道
socketChannel.close();
outChannel.close();
ssc.close();
}
}
//==========客户端==========
package com.hanker.nio1;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class TestSocketChannel {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel =
SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
// 切换成非 阻塞模式
socketChannel.configureBlocking(false);
FileChannel inputChannel =
FileChannel.open(Paths.get("1.jpeg"), StandardOpenOption.READ);
ByteBuffer clientBuffer = ByteBuffer.allocate(1024);
while (inputChannel.read(clientBuffer) != -1){
clientBuffer.flip();
socketChannel.write(clientBuffer);
clientBuffer.clear();
}
socketChannel.close();
inputChannel.close();
}
}
一次聊天:
package com.hanker.nio1;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class TestServerSocketChannel2 {
public static void main(String[] args) throws IOException {
//1.获取通道
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress(9898));//绑定链接
//2. 创建FileChannel
FileChannel outChannel = FileChannel.open(Paths.get("6.jpeg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//3.获取客户端链接的通道
SocketChannel socketChannel = ssc.accept();
//4.分配指定大小的缓冲区
ByteBuffer dst = ByteBuffer.allocate(1024);
//5.接收数据并保存
while(socketChannel.read(dst) != -1) {
dst.flip();
outChannel.write(dst);
dst.clear();
}
//6.返回信息
dst.put("服务端接收数据成功".getBytes());
dst.flip();
socketChannel.write(dst);
//7.关闭通道
socketChannel.close();
outChannel.close();
ssc.close();
}
}
//======================服务器端============
package com.hanker.nio1;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class TestSocketChannel2 {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
// 切换成非 阻塞模式
socketChannel.configureBlocking(false);
FileChannel inputChannel = FileChannel.open(Paths.get("1.jpeg"), StandardOpenOption.READ);
ByteBuffer clientBuffer = ByteBuffer.allocate(1024);
while (inputChannel.read(clientBuffer) != -1){
clientBuffer.flip();
socketChannel.write(clientBuffer);
clientBuffer.clear();
}
socketChannel.shutdownOutput();
//接收服务器的反馈
int len = 0;
while( (len = socketChannel.read(clientBuffer))!= -1 ) {
clientBuffer.flip();
System.out.println(new String(clientBuffer.array(),0,len));
clientBuffer.clear();
}
socketChannel.close();
inputChannel.close();
}
}
非阻塞模式完成客户端向服务器端传输数据
package com.hanker.nio1;
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.Date;
import java.util.Iterator;
import java.util.Scanner;
import org.junit.Test;
public class TestNonBlockingNIO {
//客户端
@Test
public void client() throws IOException{
//1.获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
//2.切换非阻塞模式
sChannel.configureBlocking(false);
//3.分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//4.发送数据给服务器
Scanner scan = new Scanner(System.in);
while(scan.hasNext()) {
String str = scan.next();
buf.put((new Date().toString() + "\n" + str).getBytes());
buf.flip();
sChannel.write(buf);
buf.clear();
}
//5.关闭通道
scan.close();
sChannel.close();
}
//服务端
@Test
public void server() throws IOException{
//1.获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
//2.切换非阻塞模式
ssChannel.configureBlocking(false);
//3.绑定链接
ssChannel.bind(new InetSocketAddress(9898));
//4.获取选择器
Selector selector = Selector.open();
//5.将通道注册到选择器,并且指定“监听接收事件”
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
//6.轮询式的获取选择器上已经“准备就绪”的事件
while(selector.select() > 0) {
//7.获取当前选择器中所有注册的“选择键(已就绪的监听事件)”
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()) {
//8.获取准备就绪的事件
SelectionKey sk = it.next();
//9.判断具体是什么事件准备就绪
if(sk.isAcceptable()) {
//10.若“接收就绪”,获取客户端链接
SocketChannel sChannel = ssChannel.accept();
//11.切换非阻塞模式
sChannel.configureBlocking(false);
//12.将该通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
}else if(sk.isReadable()) {
//13.获取当前选择器上“读就绪”状态的通道
SocketChannel sChannel =(SocketChannel) sk.channel();
//14.读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = 0;
while( (len = sChannel.read(buf))>0) {
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();
}
}
//15.取消选择键
it.remove();
}
}
}
}
先启动服务器端,再启动客户端。可以启动多个客户端进行访问。
DatagramChannel
这个与上面的非常相似,所以这里只给一个实现的代码案例:
package com.hanker.nio1;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
import org.junit.Test;
public class TestNonBlockingNIO2 {
@Test
public void send() throws IOException{
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(1024);
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String str = input.next();
buf.put( (new Date().toString()+":\n"+str).getBytes() );
buf.flip();
dc.send(buf,new InetSocketAddress("127.0.0.1",9898));
buf.clear();
}
input.close();
dc.close();
}
@Test
public void receive() throws IOException{
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while(selector.select()>0) {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()) {
SelectionKey sk = it.next();
if(sk.isReadable()) {
ByteBuffer dst = ByteBuffer.allocate(1024);
dc.receive(dst);
dst.flip();
System.out.println(new String( dst.array(),0,dst.limit() ));
dst.clear();
}
}
it.remove();
}
}
}
管道(Pipe)
Java NIO 管道是两个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
package com.hanker.nio1;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import org.junit.Test;
public class TestPipe {
@Test
public void test1() throws IOException{
//1.获取管道
Pipe pipe = Pipe.open();
//2.将缓冲区中的时速局写入管道
ByteBuffer buf = ByteBuffer.allocate(1024);
Pipe.SinkChannel sinkChannel = pipe.sink();
buf.put("通过单向管道发送数据".getBytes());
buf.flip();
sinkChannel.write(buf);
//3.读取缓冲区中的数据
Pipe.SourceChannel sourceChannel = pipe.source();
buf.flip();
int len = sourceChannel.read(buf);
System.out.println(new String(buf.array(),0,len));
sourceChannel.close();
sinkChannel.close();
}
}