Java NIO(一)

目录

Channel

JAVA NIO的通道类似流:

  • 从通道中读取数据,也可以写数据到通道,但流的读写通常是单向的

  • 通道可以异步的读写

  • 通道中的数据总是要先读到一个Buffer,或从一个Buffer中写入

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZjqZW5BT-1626700276596)(en-resource://database/1494:0)]

Channel的实现

  • FileChannel: 从文件中读写数据

  • DatagramChannle:能通过UDP读写网络中的数据

  • SocketChannel:能通过TCP读取网络中的数据

  • ServerSocketChannel:可以监听新进来的TCP连接,每个新进来的连接都会创建一个SocketChannel

简单示例

    public static void main(String[] args) throws IOException {
        RandomAccessFile file = new RandomAccessFile("./test.txt", "rw");
        FileChannel channel = file.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(48);
        int byteRead = channel.read(buffer);

        System.out.println("Read: " + byteRead);
        // 使用flip将缓冲区重置,rewind将position设置为0用于重新读取buffer数据
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println((char) buffer.get());
        }
        // clear清除所有的数据,compact只会清除已经读过的数据
        buffer.clear();
        file.close();
    }

Buffer

JAVA NIO中的Buffer用于和NIO通道进行交互。

缓冲区的本质是一块可以写入数据,然后可以从中读取数据的内存。

重要概念

  • capacity:Buffer的固定大小

  • position:当前操作的位置

  • limit:能操作的最大位置;写模式下等于capacity;读模式下等于写模式的position值

  • flip():flip方法将Buffer的写模式切换到读模式。

  • rewind():将position设置为0,重读数据

  • clear():position设置为0,limit设置为capacity的值,buffer被清空

  • compact():将未读的数据拷贝到Buffer起始处,然后清空已读数据

Scatter

读操作时将读取的数据写入多个Buffer中。

只有将前一个填满,才能使用下一个;所以不能很好的处理动态消息。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PSJL0Hen-1626700276598)(en-resource://database/1496:0)]

Gather

写操作时将多个Buffer写入同一个Channel中。

只有position和limit之间的数据才会被写入,所有能较好的处理动态消息。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PK0bZFU3-1626700276600)(en-resource://database/1498:0)]

Selector

可以只使用一个线程处理所有的通道。

Selector用于不断监听多个信道。当有信道满足事件条件时返回满足的信道数,再进行处理。

四种事件:

  • SelectionKey.OP_CONNECT

  • SelectionKey.OP_ACCEPT

  • SelectionKey.OP_READ

  • SelectionKey.OP_WRITE

三种选择方法:

  • select():阻塞到至少有一个通道在注册的事件上就绪

  • select(long timeout):最长会则色timeout毫秒

  • selectNow():不会阻塞,直接返回

示例

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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 SelectorTest {

    public static void main(String[] args) throws IOException {
        // 打开一个Selector
        Selector selector = Selector.open();
        // 创建一个服务端socket信道
        ServerSocketChannel channel = ServerSocketChannel.open();
        // 设置信道不阻塞
        channel.configureBlocking(false);
        ServerSocket serverSocket = channel.socket();
        InetSocketAddress address = new InetSocketAddress(10011);
        serverSocket.bind(address);
        // 注册信道到selector中
        channel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            int readChannels = selector.select();
            if (readChannels == 0) {
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isConnectable()) {
                    System.out.println("Connectable");
                } else if (key.isAcceptable()) {
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("Accepted connection from " + socketChannel);
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥牛火锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值