目录
Channel
JAVA NIO的通道类似流:
-
从通道中读取数据,也可以写数据到通道,但流的读写通常是单向的
-
通道可以异步的读写
-
通道中的数据总是要先读到一个Buffer,或从一个Buffer中写入
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中。
只有将前一个填满,才能使用下一个;所以不能很好的处理动态消息。
Gather
写操作时将多个Buffer写入同一个Channel中。
只有position和limit之间的数据才会被写入,所有能较好的处理动态消息。
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);
}
}
}
}
}