缓冲区
存储数据的 内存空间
JDK NIO 模块提供了 几种缓存区:
1. 堆内缓冲区
在JVM 堆 中创建的 字节数组等

比如 ByteBuffer,
构造函数通过接收 字节 数组 来作为 缓冲区的存储空间。

allocate :


2. 直接缓冲区,
在 堆 外创建的 存储空间,或者直接说成就是 在 内存条上 单独创建的存储空间,由操作系统管理
allocateDirect方法 获取



内存映射缓冲区
通道 channel
什么是通道? 通道和IO什么关系?
在网络编程中,JDK 提供了两个类,

服务端通过 ServerSocket 开启 监听,客户端通过Socket发起连接。
在ServerSocket 实例化的过程中,会创建一个 文件描述符,一个文件描述符代表一个 i/o



然后将文件描述符 和 ip 端口绑定 并开始监听端口

当调用 accept 方法接受请求时,会阻塞:

使用通道 ServerSocketChannel,调用open 方法后,也会创建一个文件描述符。



到这里,可以看到 ServerSocket 和 ServerSocketChannel 都是 会创建 文件描述符。

可以理解为,Channel 通道 是 JDK 在处理I/O时 提供的一种新的方式。可以处理网络连接。
调用 accept 接收连接。不过,通道提供了 阻塞 和 非阻塞的方式来接受连接。非阻塞方式接受请求是 通道特殊的地方。

可以看到,这里的 accept0 和 socketServer的accept0 是不同的实现类中的方法。
代码分别如下:
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8081));
serverSocketChannel.configureBlocking(false);
serverSocketChannel.accept();
选择器 Selector
什么又是选择器?
JDK的nio包里提供了一个抽象类


open()方法 返回一个 selector实例,每调用一次 返回一个新的实例

select()方法,轮询,这个方法一直阻塞 直到 有通道就绪 或者 调用了 wakeUp 方法


select(long),该方法传入一个 等待时间,单位毫秒。返回条件 和 无参 select方法一样,也是直到 有 通道就绪 或者 调用 wakeUp方法才会返回,另外就是 等待时间超过了 指定 时间也会返回。

selectNow(),该方法 立即返回,无阻塞
wakeup() ,该方法唤醒阻塞的 select() 或者 select(long)方法
跟选择器相关的一个类,SelectionKey,提供了4种类型的选择,读 写 连接 接收

至此,还是不清楚selector是什么?需要了解 IO模型,才能理解这部分内容。
IO复用模型,理解起来也不复杂,操作系统提供一个系统调用,select 函数调用后,操作系统会关注 多个指定的IO,当其中有IO就绪后,select函数返回,然后应用进程就可以 响应就绪的IO,比如读或者写操作。

小学生,用最简单的方式 写一个 NIO 服务端
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Test {
static Logger log = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
try {
// 开启 selector
Selector selector = Selector.open();
// 开启 ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
serverSocketChannel.configureBlocking(false);
// 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 监听 channel事件
int select = selector.select();
if (select == 0){
continue;
}
// 遍历 channel事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
// 连接事件
if (key.isAcceptable()){
// 这里只能是 ServerSocketChannel
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
// 获取 新的连接 channel
SocketChannel socketChannel = channel.accept();
socketChannel.configureBlocking(false);
// 设置 新的连接channel 关注的事件
// 关注 OP_READ
socketChannel.register(selector, SelectionKey.OP_READ);
}
// 读事件
if (key.isReadable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer attachment = ByteBuffer.allocate(1024);
socketChannel.read(attachment);
attachment.flip();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
log.info(new String(attachment.array()).trim());
attachment.clear();
// 关注 OP_WRITE
socketChannel.register(selector,SelectionKey.OP_WRITE);
}
// 写事件
if (key.isWritable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
// 关闭连接
key.cancel();
socketChannel.close();
}
// 移除
iterator.remove();
}
}
}catch (Exception e){
log.error("error " ,e);
}
}
}
初中生,开始想用多线程,但是写的有问题
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Test {
static Logger log = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
try {
// 开启 selector
Selector selector = Selector.open();
// 开启 ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
serverSocketChannel.configureBlocking(false);
// 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
int i=0;
while (true) {
// 监听 channel事件
int select = selector.select();
if (select == 0){
continue;
}
Thread t = new Thread(() -> {
try {
/**
* 启用一个新的线程 来处理 channel 事件。
*
* 新建立的 客户端连接 SocketChannel ,也 注册到了 当前的 selector
*
* 那么,这个线程启动之后,主线程 的 selector.select() 一直 返回 0
*/
doSelector(selector);
} catch (Exception e) {
log.error("doSelector error", e);
}
});
t.setName("doSelector-" + (i++));
t.start();
}
}catch (Exception e){
log.error("error " ,e);
}
}
private static void doSelector(Selector selector) throws IOException, InterruptedException {
// 遍历 channel事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
// 连接事件
if (key.isAcceptable()){
// 这里只能是 ServerSocketChannel
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
// 获取 新的连接 channel
SocketChannel socketChannel = channel.accept();
socketChannel.configureBlocking(false);
// 设置 新的连接channel 关注的事件
// 关注 OP_READ
socketChannel.register(selector, SelectionKey.OP_READ);
}
// 读事件
if (key.isReadable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer attachment = ByteBuffer.allocate(1024);
socketChannel.read(attachment);
attachment.flip();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
log.info(new String(attachment.array()).trim());
attachment.clear();
// 关注 OP_WRITE
socketChannel.register(selector,SelectionKey.OP_WRITE);
}
// 写事件
if (key.isWritable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
// 关闭连接
key.cancel();
socketChannel.close();
}
// 移除
iterator.remove();
}
}
}
然后 初中生 开始 改进了,但是还有问题
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Test {
static Logger log = LoggerFactory.getLogger(Test.class);
// 检测 线程启动情况
static volatile boolean start = false;
public static void main(String[] args) {
try {
// 开启 selector,只监听 客户端的连接事件
Selector selector = Selector.open();
// 开启 selector ,用来 监听 客户端的 读写事件
Selector selector2 = Selector.open();
// 开启 ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
serverSocketChannel.configureBlocking(false);
// 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
int i=0;
while (true) {
// 监听 channel事件
int select = selector.select();
if (select == 0){
continue;
}
// 将 客户端的连接事件,注册到 selector2 中
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = channel.accept();
socketChannel.configureBlocking(false);
/**
* 每次 接手到的 新的客户端连接 注册到 selector2 中,
* 第一个线程进来是好的,当有第二个连接进来时,main线程 被 block了。
*
* main线程 和 doSelector-0 线程 同时 操作 selector2,存在线程安全问题
*/
socketChannel.register(selector2, SelectionKey.OP_READ);
}
// 这个不要忘记
iterator.remove();
}
if (!start) {
Thread t = new Thread(() -> {
try {
/**
* 起一个 新的 线程,只用来处理 selector2中的 客户端的 读写事件
*/
while (true){
int count = selector2.select();
if (count == 0){
continue;
}
doSelector2(selector2);
}
} catch (Exception e) {
log.error("doSelector error", e);
}
});
t.setName("doSelector-" + (i++));
t.start();
start = true;
}
}
}catch (Exception e){
log.error("error " ,e);
}
}
private static void doSelector2(Selector selector) throws IOException, InterruptedException {
// 遍历 channel事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
// 读事件
if (key.isReadable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer attachment = ByteBuffer.allocate(1024);
socketChannel.read(attachment);
attachment.flip();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
log.info(new String(attachment.array()).trim());
attachment.clear();
// 关注 OP_WRITE
socketChannel.register(selector,SelectionKey.OP_WRITE);
}
// 写事件
if (key.isWritable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
// 关闭连接
key.cancel();
socketChannel.close();
}
// 移除
iterator.remove();
}
}
}
终于,初中生 写出了 一个 线程 处理连接事件,一个线程 处理 读写事件的 NIO 服务端
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
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.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class Test {
static Logger log = LoggerFactory.getLogger(Test.class);
// 检测 线程启动情况
static volatile boolean start = false;
// 任务队列,保存 新的连接SocketChannel
static BlockingQueue<Runnable> queue = new LinkedBlockingDeque();
public static void main(String[] args) {
try {
// 开启 selector,只监听 客户端的连接事件
Selector selector = Selector.open();
// 开启 selector ,用来 监听 客户端的 读写事件
Selector selector2 = Selector.open();
// 开启 ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress("127.0.0.1",8888));
serverSocketChannel.configureBlocking(false);
// 将 channel 注册到 selector中。 ServerSocketChannel 只能注册 OP_ACCEPT 事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
int i=0;
while (true) {
// 监听 channel事件
int select = selector.select();
if (select == 0){
continue;
}
// 将 客户端的连接事件,注册到 selector2 中
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = channel.accept();
// 将新的连接 放入 队列中
queue.add(()->{
try {
socketChannel.configureBlocking(false);
socketChannel.register(selector2, SelectionKey.OP_READ);
}catch (Exception e){
log.error("add error",e);
}
});
/**
* 为了 防止 与 selector2 绑定的 线程,在执行 selector2.select() 时 阻塞
* 这里需要 调用 selector2.wakeup(); 来唤醒
*/
selector2.wakeup();
}
// 这个不要忘记
iterator.remove();
}
if (!start) {
Thread t = new Thread(() -> {
try {
/**
* 起一个 新的 线程,只用来处理 selector2中的 客户端的 读写事件
*/
while (true){
/**
* 用非阻塞的方法 从队列中拿任务,如果拿不到则立即返回。
* 因为程序需要继续监听 已经注册到 selector2中的 事件
*/
Runnable take = queue.poll();
if (take != null){
take.run();
}
/**
* 如果 selector2中 一直 没有 事件发生,则 当前线程会一直 阻塞在这里
* 当有新的连接请求进来时,即使 队列中 存在任务,也没办法处理。
* 所以,需要在 有新连接请求时,执行 selector2.wakeup(); 来唤醒
*/
int count = selector2.select();
if (count == 0){
continue;
}
doSelector2(selector2);
}
} catch (Exception e) {
log.error("doSelector error", e);
}
});
t.setName("doSelector-" + (i++));
t.start();
start = true;
}
}
}catch (Exception e){
log.error("error " ,e);
}
}
private static void doSelector2(Selector selector) throws IOException, InterruptedException {
// 遍历 channel事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
// 读事件
if (key.isReadable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer attachment = ByteBuffer.allocate(1024);
socketChannel.read(attachment);
attachment.flip();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
log.info(new String(attachment.array()).trim());
attachment.clear();
// 关注 OP_WRITE
socketChannel.register(selector,SelectionKey.OP_WRITE);
}
// 写事件
if (key.isWritable()){
SocketChannel socketChannel = (SocketChannel) key.channel();
// 模拟业务处理时间
Thread.sleep(1000 * 3);
socketChannel.write(ByteBuffer.wrap("hello,i am server".getBytes()));
// 关闭连接
key.cancel();
socketChannel.close();
}
// 移除
iterator.remove();
}
}
}
NIO 如果只用单线程 发挥不出 其优势,必须用多线程。
一个线程 处理 连接事件
一个线程处理 读写事件
还是比较容易:
处理连接事件的线程有一个自己的 selector。有新连接请求时,将 新的连接 包装成一个 任务,丢到 队列中,并且 唤醒 读写事件的 线程
读写事件的线程也有一个自己的 selector。从队列中拿任务,如果有,则执行任务,然后处理自己的 selector
各自维护 一个 selector,通过 任务队列 来 处理 新的 连接请求。同时注意, 从队列中拿任务时,不能 用 阻塞的方法。
那么,怎么才能更大的提高效率, 用多个 处理连接请求的 线程 和 多个 处理 读写请求的 线程 来完成 NIO 服务端呢?
高中生是这样做的...

944

被折叠的 条评论
为什么被折叠?



