NIO基础知识

NIO和传统的IO有相同的作用和目的,但实现方式不同,NIO主要用到的是块,所以NIO的效率要比IO高很多。NIO和IO最大的区别是数据打包和传输方式。IO是以的方式处理数据,而NIO是以的方式处理数据。

缓冲区Buffer

Buffer是一个对象,它包含一些要写入或读出的数据。在NIO中,数据是放入Buffer对象的,而在IO中,数据是直接写入或者读到Stream对象的。应用程序不能直接对 Channel 进行读写操作,而必须通过 Buffer 来进行,即 Channel 是通过 Buffer 来读写数据的。

在NIO中,所有的数据都是用Buffer处理的,它是NIO读写数据的中转池。Buffer实质上是一个数组,通常是一个字节数据,但也可以是其他类型的数组。但一个缓冲区不仅仅是一个数组,重要的是它提供了对数据的结构化访问,而且还可以跟踪系统的读写进程。

Buffer的类型

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

使用Buffer读写数据的一般步骤

  1. 写入数据到Buffer
  2. 调用flip()方法
  3. 从Buffer中读取数据
  4. 调用clear()方法或者compact()方法,其中clear()方法会清除整个缓冲区,compact()方法只会清除已经读过的数据。

Buffer几个重要的概念

// Invariants: mark <= position <= limit <= capacity
private int mark = -1; // 记住目前的position,调用reset()方法可以将position变回之前记住的位置
private int position = 0; // 用于指明下一个可以被读出的或者写入的缓冲区位置索引。
private int limit; // 第一个不应该被读出或者写入的缓冲区位置索引。也就是说,位于limit后的数据既不可被读,也不可以被写。
private int capacity; // 缓冲区的容量表示该Buffer的最大数据容量,缓冲区的容量不能为负值,创建后不能改变。

Buffer的flip()clear()方法

public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
 }
/*
把当前的指针位置position设置成了limit,再将当前指针position指向数据的最开始端,我们现在可以将数据从缓冲区写入通道了。 position 被设置为 0,这意味着我们得到的下一个字节是第一个字节。 limit 已被设置为原来的 position,这意味着它包括以前读到的所有字节,并且一个字节也不多。如下图所示
*/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-32zLo1in-1586147485664)(http://owbl44q3i.bkt.clouddn.com/flip.jpg)]

public final Buffer clear() {
    position = 0;
    limit = capacity;
    mark = -1;
    return this;
}
/*
重设缓冲区以便接收更多的字节,如下图
*/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JCXm9mJA-1586147485668)(http://owbl44q3i.bkt.clouddn.com/clear.jpg)]

通道Channel

Channel是一个通道,既可以从通道中读取数据,又可以写数据到通道,即Channel是全双工的。Channel可以进行异步的读写。对Channel的读写必须通过buffer对象

Channel的主要类型

  1. FileChannel:从文件读取数据的
  2. DatagramChannel:读写UDP网络协议数据
  3. SocketChannel:读写TCP网络协议数据
  4. ServerSocketChannel:可以监听TCP连接

所有的Channel都不能通过构造器来直接创建,而是通过传统的节点的getChannel()方法来返回对应的Channel。

FileChannel

FileChannel是一个连接到文件的通道。可以通过文件通道读写文件。

打开FileChannel

通过使用一个InputStream、OutputStream或RandomAccessFile等IO流来获取一个FileChannel实例。

FileChannel inChannel = new FileInputStream("filename").getChannel;

从FileChannel读取数据

ByteBuffer buffer = ByteBuffer.allocate(capacity);
int bytesRead = inChannel.read(buffer); // read方法返回-1则到达文件末尾

写入数据到FileChannel

  • 获取一个通道:FileChannel outChannel = new FileOutputStream("filename").getChannel;
  • 创建缓冲区,将数据放入缓冲区
ByteBuffer buffer = ByteBuffer.allocate( capacity );
for (int i = 0; i < message.length; ++i) {
 	buffer.put( message[i] );
}
buffer.flip();
  • 把缓冲区数据写入通道中:outChannel.write(buffer);

Channel与Buffer的例子

public class ReadFile {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("ReadFile.java");
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(256);
        
        while (fileChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            Charset charset = Charset.forName("UTF-8");
            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer charBuffer = decoder.decode(byteBuffer);
            System.out.println(charBuffer);
            byteBuffer.clear();
        }

        fileChannel.close();
        fileInputStream.close();
    }
}

SocketChannel

SocketChannel是一个连接到TCP网络套接字的通道。

打开SocketChannel

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://www.baidu.com/", 8080));

从SocketChannel读取数据

ByteBuffer buf = ByteBuffer.allocate(256);
int bytesRead = socketChannel.read(buf);

写入数据到SocketChannel

String newData = "New String to write to file...";

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
    channel.write(buf);
}

非阻塞模式

可以设置 SocketChannel 为非阻塞模式(non-blocking mode)。设置之后,就可以在异步模式下调用connect(),read() 和write()了。

connect()

如果SocketChannel在非阻塞模式下,此时调用connect(),该方法可能在连接建立之前就返回了。为了确定连接是否建立,可以调用finishConnect()的方法。

socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://www.baidu.com/", 8080));
while (!socketChannel.finishConnect()) {
    // wait, or do something else
}

ServerSocketChannel

ServerSocketChannel 是一个可以监听新进来的TCP连接的通道

// 打开ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
while (true) {
    // 监听连接
    SocketChannel socketChannel = serverSocketChannel.accept();
    //do something with socketChannel...
}

非阻塞模式

// 在非阻塞模式下,accept() 方法会立刻返回,如果还没有新进来的连接,返回的将是null
// 打开ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
serverSocketChannel.configureBlocking(false);
while (true) {
    // 监听连接
    SocketChannel socketChannel = serverSocketChannel.accept();
    if (socketChannel != null) {
        //do something with socketChannel...
    }
}

DatagramChannel

DatagramChannel是一个能收发UDP包的通道。

打开DatagramChannel

DatagramChannel channel = DatagramChannel.open();
// 可以在UDP端口8080上接收数据包
channel.socket().bind(new InetSocketAddress(8080));

接收数据

ByteBuffer buf = ByteBuffer.allocate(256);
buf.clear();
// 通过receive()方法从DatagramChannel接收数据
// receive()方法会将接收到的数据包内容复制到指定的Buffer. 如果Buffer容不下收到的数据,多出的数据将被丢弃。
channel.receive(buf);

发送数据

String newData = "New String to write to file...";

ByteBuffer buf = ByteBuffer.allocate(256);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
// 通过send()方法从DatagramChannel发送数据
int bytesSent = channel.send(buf, new InetSocketAddress("http://www.baidu.com/", 8080));

多路复用器Selector

Selector 允许一个单一的线程来操作多个 Channel,Selector会不断地轮询注册在其上的Channel,如果某个Channel上面发生读或写事件,这个Channel就处于就绪状态,会被Selector轮询出来,然后通过SelectionKey可以获取Channel的集合,进行后续的IO操作。

Selector的创建Selector selector = Selector.open();

向Selector中注册通道

channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);

只有非阻塞的Channel才能注册到Selector里面,即上面的代码channel.configureBlocking(false); 这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式

register()方法的第二个参数。这是一个“interest集合”,意思是在通过Selector监听Channel时对什么事件感兴趣。可以监听四种不同类型的事件:

  1. Connect:连接事件(TCP连接),用常量SelectionKey.OP_CONNECT表示。
  2. Accept:确认事件, 用常量SelectionKey.OP_ACCEPT表示
  3. Read: 读事件, 用常量于SelectionKey.OP_READ表示
  4. Write:写事件, 常量SelectionKey.OP_WRITE表示

也可以表示多种事件,可以用“位或”操作符将常量连接起来,如下

int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;

SelectionKey

register()方法会返回一个SelectionKey对象,这个对象包括以下属性

  1. interest集合
  2. ready集合
  3. Channel
  4. Selector
  5. 附加的对象(可选)

interest集合

interest集合是你所选择的感兴趣的事件集合。可以通过SelectionKey读写interest集合

int interestSet = selectionKey.interestOps();

boolean isInterestedInAccept  = interestSet & SelectionKey.OP_ACCEPT;
boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;
boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;
boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE;

用“位与”操作interest 集合和给定的SelectionKey常量,可以确定某个确定的事件是否在interest 集合中。

ready集合

ready 集合是通道已经准备就绪的操作的集合。在一次选择(Selection)之后,会首先访问这个ready set。

// 访问ready集合
int readySet = selectionKey.readyOps();

// 检测channel中什么事件或操作已经就绪
selectionKey.isAcceptable();
selectionKey.isConnectable();
selectionKey.isReadable();
selectionKey.isWritable();

Channel + Selector

从SelectionKey访问Channel和Selector很简单。如下:

Channel channel = selectionKey.channel();
Selector selector = selectionKey.selector();

附加的对象

可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:

selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment();

还可以在用register()方法向Selector注册Channel的时候附加对象。如:

SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);

通过Selector选择Channel

一旦向Selector注册了一或多个通道,就可以调用几个重载的select()方法。这些方法返回你所感兴趣的事件(如连接、接受、读或写)已经准备就绪的那些通道。

int select(); // 阻塞到至少有一个通道在你注册的事件上就绪了。
int select(long timeout); // 和select()一样,除了最长会阻塞timeout毫秒(参数)。
int selectNow(); // 不会阻塞,不管什么通道就绪都立刻返回

// select()方法返回的int值表示有多少通道已经就绪。即自上次调用select()方法后有多少通道变成就绪状态

遍历这个已选择的键集合来访问就绪的通道

Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
    SelectionKey key = keyIterator.next();
    if(key.isAcceptable()) {
        // a connection was accepted by a ServerSocketChannel.
    } else if (key.isConnectable()) {
        // a connection was established with a remote server.
    } else if (key.isReadable()) {
        // a channel is ready for reading
    } else if (key.isWritable()) {
        // a channel is ready for writing
    }
    keyIterator.remove();
}

每次迭代末尾的会有一次keyIterator.remove()调用。Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。

SelectionKey.channel()方法返回的通道需要转型成你要处理的类型,如ServerSocketChannel或SocketChannel等。

wakeUp()

某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其它线程在第一个线程调用select()方法的那个对象上调用Selector.wakeup()方法即可。阻塞在select()方法上的线程会立马返回。

close()

用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效。通道本身并不会关闭。

完整示例

// 以Socket通信为例
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
Selector selector = Selector.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
serverSocketChannel.configureBlocking(false);
SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
  int readyChannels = selector.select();
  if(readyChannels == 0) continue;
  Set selectedKeys = selector.selectedKeys();
  Iterator keyIterator = selectedKeys.iterator();
  while(keyIterator.hasNext()) {
    SelectionKey key = keyIterator.next();
    if(key.isAcceptable()) {
        // a connection was accepted by a ServerSocketChannel.
        SocketChannel channel = ((ServerSocketChannel) key.channel()).accept();
        channel.configureBlocking(false);
        channel.register(key.selector(), OP_READ, ByteBuffer.allocate(256));
    } else if (key.isConnectable()) {
        // a connection was established with a remote server.
    } else if (key.isReadable()) {
        // a channel is ready for reading
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buf = (ByteBuffer) key.attachment();
        long bytesRead = channel.read(buf);
        if (bytesRead == -1) {
            channel.close();
        } else if (bytesRead > 0) {
            key.interestOps(OP_READ | SelectionKey.OP_WRITE);
            System.out.println(bytesRead);
        }
    } else if (key.isWritable()) {
        // a channel is ready for writing
    }
    keyIterator.remove();
  }
}

参考链接:http://ifeve.com/java-nio-all/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值