一阶段:第16天:NIO(8.13)
一.概述
- 为所有的原始类型(boolean类型除外)提供缓存支持的数据容器,提供非阻塞式的高伸缩性网络。
- IO操作的模式:
(1)PIO(Programing IO): 所有的IO操作由CPU处理,CPU占用率比较高 。
(2)DMA(Direct Memory Access):CPU把IO操作控制权交给DMA控制器,只能以固定的方式读写,CPU空闲做其他工作。
(3)通道方式(Channel):能执行有限通道指令的IO控制器,代替CPU管理控制外设。通道有自己的指令系统,是一个协处理器,具有更强的独立处理数据输入和输出的能力。 - NIO的核心部分:a.Buffer:缓冲区;b.Channel:通道;c.Selector:选择器(轮询器)
- NIO和IO的区别:IO:a.Stream:面向流;b.阻塞IO;c.无选择器
NIO:a.Buffer:面向缓冲区;b.非阻塞IO;c.有选择器
二.Buffer的使用
- Buffer的实现类:ByteBuffer,CharBuffer,DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer,ShortBuffer
- 使用Buffer读写数据一般遵循以下四个步骤:
- 创建缓冲区,写入数据到Buffer
- 调flip()方法—吧写入模式转换成读取模式
- 从Buffer中读取数据
- 调用clear()方法或者compact()方法。clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。
Buffer缓冲区的使用
public class Demo1 {
public static void main(String[] args) {
//1.创建缓冲区,容量1024
ByteBuffer buffer=ByteBuffer.allocate(1024);
//2.写入数据
buffer.put("helloworld".getBytes());
//3.读取数据
//3.1把写入模式,转换成读取模式
buffer.flip();
//3.2读取
/*//单个字节读取
byte b=buffer.get();
System.out.println((char)b);*/
//ctrl+alt+v--->补全代码
byte[] data=new byte[buffer.limit()];//limit--->有多少个能读,就是多长
buffer.get(data);
System.out.println(new String(data));
//4.清空
buffer.clear();
}
}
重点:
* Buffer--->缓冲流
* Buffer的实现原理
* // Invariants: mark <= position <= limit <= capacity
* private int mark = -1;//标记
* private int position = 0;//位置
* private int limit;//限制
* private int capacity;//容量
public class Demo2 {
public static void main(String[] args) {
ByteBuffer buffer=ByteBuffer.allocate(1024);
System.out.println("---写入数据之前---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
buffer.put("hello".getBytes());
System.out.println("---写入数据之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
//把写入模式切换成读取模式
buffer.flip();//初始模式是写入模式
System.out.println("---切换为读取模式之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
//读取
byte[] data = new byte[buffer.limit()];
buffer.get(data);
System.out.println("---读取完之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
//rewind(),将position设回0,可以重读Buffer中的所有数据;
buffer.rewind();
System.out.println("---rewind()---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
//compact
byte b1 = buffer.get();
byte b2 = buffer.get();
byte b3 = buffer.get();
System.out.println("---读取3个字节之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
buffer.compact();//与clear的意义类似,都有清空重置的意思,所以如果还想读,就需要再转一下
System.out.println("---compact()之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
buffer.flip();//???为什么还要转---解决
byte b4 = buffer.get();
byte b5 = buffer.get();
System.out.println((char)b4);
System.out.println((char)b5);
System.out.println("---在读取两个之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
//清空
buffer.clear();//数据还有,只是更改了指针,下次输入时将其覆盖
System.out.println("---清空之后---");
System.out.println("容量"+buffer.capacity());
System.out.println("限制"+buffer.limit());
System.out.println("位置"+buffer.position());
//若清空之后不转换为读文件模式,那么限制将会为写的长度,可以一直读下去,但是都是没有数据,或数据不符的值
//读写转换主要影响位置指针和限制指针,并不影响实际的读和写,只是数据很有可能不符,eg:数据是之前的或为空(读),把原来的数据覆盖了(写)
byte b = buffer.get(0);//若没有值,默认是‘0’
System.out.println((char)b);//在没覆盖前,数据还在,
}
}
public class Demo3 {
public static void main(String[] args) {
ByteBuffer buffer=ByteBuffer.allocateDirect(1024);
buffer.put("hello".getBytes());
buffer.flip();
byte[] data=new byte[2];
buffer.get(data);
System.out.println("第一次读取");
System.out.println(new String(data));
buffer.mark();//标记--->不能做太多,最好就只做一个标记
buffer.get(data);
System.out.println("第二次读取");
System.out.println(new String(data));
buffer.reset();//回到上一个标记的位置
buffer.get(data);
System.out.println("第三次读取");
System.out.println(new String(data));
}
}
三.Channel
非直接缓冲区的使用:
- ByteBuffer.allocate()
直接缓冲区的使用:
- 通过ByteBuffer.allocateDirect(),创建直接缓冲区
- 通过内存映射文件的方式:通过mapBuffer进行传输
- 使用通道直接传输:只有FileChannel有这个方式FileChannel.open(),不需要借助缓冲区
- 优点:速度更快,效率更高
- 缺点:①更多消耗②后续写入磁盘等操作完全由操作系统决定,不受我们控制
- 适用范围:数据复用率高,或者大数据量的操作(大文件才能体现出速度优势)
- JAVA NIO中的一些主要Channel的实现:FileChannel、DatagramChannel、SocketChannel、ServerSocketChannel
- FileChannel是一个连接到文件的通道。可以通过文件通道读写文件。无法设置为非阻塞模式,它总是运行在阻塞模式下。
- 在使用FileChannel之前,必须先创建它。创建方式有两种:
(1)使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。
(2)JDK1.7之后才能使用, FileChannel.open()方法。 - 用完FileChannel后必须将其关闭。(channel.close();)
读取文件:
public class Demo1 {
public static void main(String[] args) throws Exception{
/*File file=new File("info.txt");
file.createNewFile();*/
/* //创建随机读取文件
RandomAccessFile raf=new RandomAccessFile("info.txt", "r");
//获取通道
FileChannel channel=raf.getChannel();*/
//Paths.get("info.txt", "");
FileChannel channel=FileChannel.open(Paths.get("info.txt", ""),StandardOpenOption.READ);
//读取
ByteBuffer buf=ByteBuffer.allocate(1024);
while (channel.read(buf)>0){//为0或-1都是没数据,当没数据时有两种取值,都得考虑到
//切换为读模式
buf.flip();
String data=new String(buf.array(),0,buf.limit());//buf.array--->数组缓冲区,就是那个数组:byte[] data=new byte[buf.limit()];
System.out.println(data);
buf.clear();
}
//关闭
channel.close();
//raf.close();
}
}
写入文件:
public class Demo2 {
public static void main(String[] args) throws Exception{
//1.创建通道
//FileChannel fileChannel=FileChannel.open(Paths.get("hello.txt"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
FileChannel fileChannel=FileChannel.open(Paths.get("hello.txt"), StandardOpenOption.WRITE,StandardOpenOption.CREATE,StandardOpenOption.APPEND);
//2.写入
ByteBuffer buf=ByteBuffer.allocate(1024);
for (int i = 0; i < 10; i++) {
buf.put("好好学习\r\n".getBytes());
buf.flip();
fileChannel.write(buf);
buf.clear();//不加容易超出范围
}
//关闭
fileChannel.close();
}
}
非直接缓冲流:复制大文件,速度慢
使用FileChannel复制图片:
public class Copy {
public static void main(String[] args) throws Exception{
FileChannel readChannel=FileChannel.open(Paths.get("aaa.jpg", ""), StandardOpenOption.READ);
FileChannel writeChannel=FileChannel.open(Paths.get("bbb.jpg", ""), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
ByteBuffer buf=ByteBuffer.allocate(1024);
while (readChannel.read(buf)>0){
buf.flip();
writeChannel.write(buf);
buf.clear();
}
readChannel.close();
writeChannel.close();
System.out.println("复制完成");
}
}
* 使用内存映射文件复制,在直接内存中开辟空间
* 适合大文件的复制
* 如果文件超过2G,最好分开映射
public class Copy2 {
public static void main(String[] args) throws Exception{
FileChannel readChannel=FileChannel.open(Paths.get("001.wmv", ""), StandardOpenOption.READ);
FileChannel writeChannel=FileChannel.open(Paths.get("002.wmv", ""), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//分开映射
MappedByteBuffer map1 = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, 1024*1024*50);//后面那个是偏移量
MappedByteBuffer map2 = readChannel.map(FileChannel.MapMode.READ_ONLY, 1024*1024*50, 1024*1024*50);
MappedByteBuffer map3 = readChannel.map(FileChannel.MapMode.READ_ONLY, 1024*1024*100, readChannel.size()-1024*1024*100);
/*MappedByteBuffer map = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, readChannel.size());
writeChannel.write(map);*/
writeChannel.write(map1);
writeChannel.write(map2);
writeChannel.write(map3);
readChannel.close();
writeChannel.close();
System.out.println("复制完毕");
}
}
四. Selector和非阻塞网络编程
4.1ServerSocketChannel、SocketChannel实现阻塞式网络编程
* 使用NIO实现TCP的服务器端(阻塞式)
* ServerSocketChannel服务器套接字通道
* SocketChannel客户端套接字通道
public class TcpServer {
public static void main(String[] args) throws Exception{
//1.创建ServerSocketChannel
ServerSocketChannel listener=ServerSocketChannel.open();
//2.绑定端口号 SocketAddress 套接字地址(ip地址+端口号)、InetAddress(ip地址,不包含端口号)
listener.bind(new InetSocketAddress("10.9.21.154", 9999));
//3.监听
System.out.println("---服务器已启动---");
SocketChannel socketChannel = listener.accept();//默认还是阻塞的
//4.读取数据
ByteBuffer buffer=ByteBuffer.allocate(1024*4);
int len=-1;
while ((len=socketChannel.read(buffer))>0) {//read也会阻塞,不会返回如果客户端关闭或结束返回-1,永远不会返回0
buffer.flip();//转成读取模式
String data=new String(buffer.array(),0,buffer.limit());
System.out.println(len);
InetSocketAddress isa= (InetSocketAddress) socketChannel.getRemoteAddress();
System.out.println(socketChannel.getRemoteAddress()+"说:"+data);
System.out.println("-----");
System.out.println(isa.getAddress().getHostAddress()+"说:"+data);
buffer.clear();
}
System.out.println(len);
//5.关闭
listener.close();
socketChannel.close();
}
}
* 使用NIO实现client
public class TcpClient {
public static void main(String[] args) throws Exception{
//1.创建客户端套接字通道,并连接
SocketChannel sc=SocketChannel.open(new InetSocketAddress("10.9.21.154",9999));
//2.写入
ByteBuffer byteBuffer=ByteBuffer.allocate(1024*4);
byteBuffer.put("好久不见".getBytes());
byteBuffer.flip();
sc.write(byteBuffer);
//3.关闭
sc.close();
}
}
4.2 Selector(实现非阻塞)
- Selector 允许单线程处理多个Channel。仅用单个线程来处理多个Channels的好处是,只需要更少的线程来处理通道。事实上,可以只用一个线程处理所有的通道,这样会大量的减少线程之间上下文切换的开销。
- 选择器(Selector): Selector选择器类管理着一个被注册的通道集合的信息和它们的就绪状态。通道是和选择器一起被注册的,并且使用选择器来更新通道的就绪状态。
可选择通道(SelectableChannel): SelectableChannel这个抽象类提供了实现通道的可选择性所需要的公共方法。它是所有支持就绪检查的通道类的父类。因为FileChannel类没有继承SelectableChannel因此不是可选通道,而所有socket通道都是可选择的,SocketChannel和ServerSocketChannel是SelectableChannel的子类。
选择键(SelectionKey): 选择键封装了特定的通道与特定的选择器的注册关系。选择键对象被SelectableChannel.register()返回并提供一个表示这种注册关系的标记。选择键包含了两个比特集(以整数的形式进行编码),选择键支持四种操作类型:
- Connect 连接
- Accept 接受请求
- Read 读
- Write 写
Java中定义了四个常量来表示这四种操作类型:
SelectionKey.OP_CONNECT
SelectionKey.OP_ACCEPT
SelectionKey.OP_READ
SelectionKey.OP_WRITE
实现非阻塞式网络通信:
* 使用一个线程处理多个客户端请求(使用非阻塞网络编程)selector
public class TcpServer {
public static void main(String[] args) throws Exception{
//1.创建ServerSocketChannel
ServerSocketChannel listener=ServerSocketChannel.open();
//2.绑定地址
listener.bind(new InetSocketAddress("10.9.21.154",9999));
//3.设置为非阻塞式
listener.configureBlocking(false);//true--->阻塞;false--->非阻塞
//4.创建Selector(轮询器)
Selector selector=Selector.open();
//5.注册轮询器
listener.register(selector, SelectionKey.OP_ACCEPT);
//6.轮询处理
//select()是一个阻塞方法,当轮询器有事件发生则返回个数--->即有人连
while (selector.select()>0){
//哪些键--->集合
//获取所有的事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
while (it.hasNext()){
SelectionKey selectionKey=it.next();
//判断事件类型
if (selectionKey.isAcceptable()){//有新的客户连接
//8.处理请求
SocketChannel socketChannel = listener.accept();//不会阻塞了,因为肯定有人连接
//9.设置非阻塞模式
socketChannel.configureBlocking(false);
//10.注册轮询器
socketChannel.register(selector, SelectionKey.OP_READ);
}else if(selectionKey.isReadable()){//新的数据发送过来
//接受数据
//11.获取发生读取时间的SocketChannel
SocketChannel sc=(SocketChannel)selectionKey.channel();
//12.创建ByteBuffer
ByteBuffer buf=ByteBuffer.allocate(1024*4);
int len=-1;
InetSocketAddress isa=(InetSocketAddress) sc.getRemoteAddress();
try {
//read()不会阻塞,没有数据返回0,有数据返回数据个数,结束返回-1
while ((len=sc.read(buf))>0){
buf.flip();
String data=new String(buf.array(),0,buf.limit());
//InetSocketAddress isa=(InetSocketAddress) sc.getRemoteAddress();
System.out.println(isa.getAddress().getHostAddress()+"说:"+data);
buf.clear();
}
} catch (IOException e) {
System.out.println(isa.getAddress().getHostAddress()+"退出了");
}
if (len==-1){
sc.close();//关闭ScoketChannel
}
}
//把处理过的事件删除掉
it.remove();
}
}
}
}
public class TcpClient {
public static void main(String[] args) throws Exception{
//1.创建SocketChannel
InetSocketAddress isa=new InetSocketAddress("10.9.21.154",9999);
SocketChannel sc=SocketChannel.open(isa);
//2.设置为非阻塞
sc.configureBlocking(false);
//3.写入数据
Scanner input=new Scanner(System.in);
ByteBuffer buf=ByteBuffer.allocate(1024*4);
while (true){
String d=input.next();
buf.put(d.getBytes());
buf.flip();
sc.write(buf);
buf.clear();
if (d.equals("baibai")){
break;
}
}
//4.关闭
sc.close();
}
}