NIO

1. NIO的三个重要组成部分

1.1 缓冲区

底层是数组,作用是存数据。
分类
ByteBuffer
CharBuffer
ShortBuffer
IntBuffer
LongBuffer
FloatBuffer
DoubleBuffe

1.1.1 直接缓冲区

建立在物理内存中,提高效率。
获取方法
ByteBuffer bb = ByteBuffer.allocateDirect(1024);

1.1.2 非直接缓冲区

建立在jvm内存中。
获取方法
ByteBuffer bb = ByteBuffer.allocate(1024);

1.1.3 缓冲区的四个核心属性

  1. capacity: 容量,表示缓冲区中最大存储数据的容量,一但声明不能改变。(因为底层是数组,数组一但被创建就不能被改变)

  2. limit: 界限,表示缓冲区中可以操作数据的大小。(limit后数据不能进行读写)

  3. position: 位置,表示缓冲区中正在操作数据的位置
    position <= limit <= capacity

  4. mark:标记,表示记录当前position的位置,可以通过reset()恢复到mark的位置。

1.1.4 缓冲区的常用方法

  1. allocate():工程模式的方法,构建缓存区,并分配大小。
  2. put():写数据byte数组。
  3. flip():切换到读取数据模式
  4. get():读取数据
  5. rewind():重复读取数据,使position归0
  6. clear():清空缓冲区,但是缓冲区中的数据依然存在,只是处于一种“被遗忘“的状态。只是不知道位置界限等,读取会有困难。
  7. mark():标记。mark会记录当前的position,limit,capacity
  8. reset():position,limit,capacity恢复到mark记录的位置

1.2 通道

通道(Channel)表示IO源与目标打开的连接。Channel类似于传统的”流“,只不过Channel本身不能直接访问数据,Channel只能与Buffer进行交互。

1.2.1 本地的数据通道

  1. FileChannel

获取方式:
FileInputStream.getChannel()
FileOutputStream.getChannel()

1.2.2 网络编程的通道

  1. SocketChannel
  2. ServerSocketChannel
  3. DatagramChannel

获取方式:
Socket.getChannel()
ServerSocket.getChannel()
DatagramSocket.getChannel()

1.2.3 其他获取方式

  1. FileChannel.open(Paths.get(…),读写状态);
FileChannel inputChannel = FileChannel.open(
Paths.get("H:\\img\\9.jpg"), //这个参数代表地址
StandardOpenOption.READ//这个参数代表对管道的读写状态
);
  1. Files工具类的 newByteChannel();

2. 使用直接缓存区和非直接缓存区,来复制文件

2.1 非直接缓冲区复制文件

//1.使用非直接缓冲区进行文件复制
public void test01() {
	try {
		//1.获取读流、写流
		FileInputStream fis = new FileInputStream("D:\\新建文件夹\\01.jpg");
		FileOutputStream fos = new FileOutputStream("D:\\新建文件夹\\02.jpg");
		//2.通过读流写流,获取管道
		FileChannel fic = fis.getChannel();
		FileChannel foc = fos.getChannel();
		//3.定义缓冲区
		ByteBuffer bb = ByteBuffer.allocate(1024);
		//4.获取读流管道中的数据,写入到缓冲区中,根据缓冲区大小来读
		while(fic.read(bb)!=-1) {
		//5.数据写到缓冲区后,将缓冲区设置为读状态
			bb.flip();
		//6.将缓冲区的数据写入到管道中
			foc.write(bb);
		//7.清空缓冲区
			bb.clear();
		}
	} catch (Exception e) {
		// TODO: handle exception
	}
}

2.2 直接缓冲区复制文件

public static void test02() {
	try {
		//1.使用open直接获取管道
		FileChannel inputChannel = FileChannel.open(Paths.get("D:\\新建文件夹\\01.jpg"), StandardOpenOption.READ);
		FileChannel outputChannel = FileChannel.open(Paths.get("D:\\新建文件夹\\03.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
		//2.使用内存映射文件,将管道中的数据映射到文件中,看起来好像是缓冲区
		MappedByteBuffer inputBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputChannel.size());
		MappedByteBuffer outputBuffer = outputChannel.map(FileChannel.MapMode.READ_WRITE, 0, inputChannel.size());
		//3.将一个缓存区的数据写入到另一个缓冲区中
		byte [] bytes = new byte[inputBuffer.limit()];
        inputBuffer.get(bytes);
        outputBuffer.put(bytes);
        //4.关闭
        inputChannel.close();
        outputChannel.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

2.3通道之间也可以进行数据参数

public void ChannelTest3() throws IOException {
     FileChannel inputChannel = FileChannel.open(Paths.get("H:\\img\\12.jpg"), StandardOpenOption.READ);
     FileChannel outputChannel = FileChannel.open(Paths.get("H:\\img\\haha.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE);
     // 两种方式都行
     //inputChannel.transferTo(0,inputChannel.size(),outputChannel);
     outputChannel.transferFrom(inputChannel,0,inputChannel.size());
     
     inputChannel.close();
     outputChannel.close();
 }

3. 网络通信

3.1非阻断模式

客户代码

private static void cle() throws Exception{
		SocketChannel sc = SocketChannel.open(new InetSocketAddress("192.168.3.13",8989));
		sc.configureBlocking(false);
		ByteBuffer bb = ByteBuffer.allocate(1024);
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()) {
			String next = scanner.next();
			bb.put(next.getBytes());
			bb.flip();
			sc.write(bb);
			bb.clear();
			sc.close();
		}
		
	}

服务代码

/*
1.获取通道
 2.切换非阻塞模式
 3.绑定连接
 4.获取选择器
 5.通道与选择器绑定,并指定“监听接收事件”
 6.轮询式的获取选择器上已“准备就绪”的事件
 7.获取当前选择器所有注册的“选择键(已就绪的监听事件)”
 8.获取准备“就绪”的事件
 9.判断具体是什么事件准备就绪
 10.若“接收就绪”,获取客户连接
 11.切换非阻塞模式
 12.将该通道注册到服务器上
 13.获取当前选择器上的“读就绪”状态的通道
 14.读取数据
 15.取消选择键
 */
private static void server() throws Exception{
	/*
	 ssc的状态:有连接,有多少个连接,没有连接
	 Selector监听这个通道的连接,
	 
	 Selector:监听器
	 selector中有很多SelectionKey,通过select()可以查看多少
	  SelectionKey:监听事件
	 */
	//1.获取通道
	ServerSocketChannel ssc = ServerSocketChannel.open();
	//2.切换非阻塞模式
	ssc.configureBlocking(false);
	//3.绑定连接
	ssc.bind(new InetSocketAddress("192.168.3.13",8989));
	//4.获取选择器
	Selector selector = Selector.open();
	//5.通道与选择器绑定,并指定“监听接收事件”
	ssc.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 sc = ssc.accept();
	//11.切换非阻塞模式
				sc.configureBlocking(false);
	//12.将该通道注册到服务器上
				sc.register(selector, SelectionKey.OP_READ);
	//13.获取当前选择器上的“读就绪”状态的通道
			}else if (sk.isReadable()) {
	//14.读取数据
				SocketChannel sc = (SocketChannel) sk.channel();
				ByteBuffer bb = ByteBuffer.allocate(1024);
				int len = 0;
				while((len = sc.read(bb)) > 0) {
					System.out.println(new String(bb.array(),0,bb.limit()));
					bb.clear();
				}
			}
	//15.取消选择键
			it.remove();
		}
	}
}

3.2 阻断代码

客户端代码

private static void cle() throws IOException {
		// TODO Auto-generated method stub
		SocketChannel sc = SocketChannel.open(new InetSocketAddress("192.168.3.13", 8989));
		FileChannel fc = FileChannel.open(Paths.get("D:\\新建文件夹\\01.jpg"), StandardOpenOption.READ);
		ByteBuffer bb = ByteBuffer.allocate(1024);
		while(fc.read(bb)!=-1) {
			bb.flip();
			sc.write(bb);
			bb.clear();
		}
		sc.shutdownOutput();
		int len = 0;
		while((len = sc.read(bb))!=-1) {
			System.out.println(new String(bb.array(),0,len));
		}
		sc.close();
		fc.close();
		
	}

服务端

private static void server() throws IOException {
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ssc.bind(new InetSocketAddress(8989));
		SocketChannel sc = ssc.accept();
		ByteBuffer bb = ByteBuffer.allocate(1024);
		FileChannel fc = FileChannel.open(Paths.get("D:\\新建文件夹\\02.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
		while(sc.read(bb)!=-1) {
			bb.flip();
			fc.write(bb);
			bb.clear();
		}
		bb.put("上传完成".getBytes());
		bb.flip();
		sc.write(bb);
		sc.shutdownInput();
		sc.close();
		ssc.close();
	}

3.3 传统IO流形式

不写了

3.4 DatagramChannel形式

@Test
    public void send() throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open();

        datagramChannel.configureBlocking(false);

        String str = "随便写写,测试一下";

        ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
        sendBuffer.put(str.getBytes());
        sendBuffer.flip();

        datagramChannel.send(sendBuffer,new InetSocketAddress("127.0.0.1",7498));
        sendBuffer.clear();

        datagramChannel.close();
    }

    @Test
    public void recive() throws IOException{
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.configureBlocking(false);
        datagramChannel.bind(new InetSocketAddress(7498));

        Selector selector = Selector.open();

        datagramChannel.register(selector,SelectionKey.OP_READ);

        while (selector.select() > 0){
            Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();

            while (selectionKeyIterator.hasNext()){
                SelectionKey key = selectionKeyIterator.next();

                if (key.isReadable()){
                    ByteBuffer reciveBuffer = ByteBuffer.allocate(1024);

                    datagramChannel.receive(reciveBuffer);
                    reciveBuffer.flip();
                    System.out.println(new String(reciveBuffer.array(),0,reciveBuffer.limit()));
                    reciveBuffer.clear();
                }
            }
            selectionKeyIterator.remove();
        }
        datagramChannel.close();
    }

4.管道(Pipe)

Java NIO 管道是两个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

在这里插入图片描述

@Test
    public void test() throws IOException {
        // 获取管道
        Pipe pipe = Pipe.open();

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 将缓冲区中数据写入管道
        Pipe.SinkChannel sinkChannel = pipe.sink();
        buffer.put("要死了要死了要死了,,,救救孩子吧".getBytes());
        buffer.flip();
        sinkChannel.write(buffer);

        // 为了省事,就不写两个线程了
        // 读取缓冲区中数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        buffer.flip();

        System.out.println(new String(buffer.array(),0,sourceChannel.read(buffer)));

        sinkChannel.close();
        sourceChannel.close();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值