一、nio
1、Buffer
-
Non-Direct Buffer:内存分配在java堆中 使用数组存储
-
Direct Buffer:通过Unsafe类 直接将内存分配在native堆上 然后使用mapping进行内存映射 减少了一次内存拷贝 直接缓存使用Cleaner进行内存回收
buff主要分为直接缓存和内存缓存
直接换成使用native层内存 减少了一次内存拷贝 提高效率
内存缓存使用byte数组进行存储
1.1、主要类
Buffer 覆盖了能从 IO 中传输的所有的 Java 基本数据类型.
主要有ByteBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBuffer、CharBuffer
主要类中有一些子类
| 类名 | 说明 |
|---|---|
| HeapXXBuffer | 将内存分配在java堆上(即数组) |
| DirectXXBuffer | 使用unsafe分配native堆内存 |
| XXBufferR | 只读缓存 |
| XXBufferB | 使用ByteBuffer存储 以大端格式 |
| XXBufferL | 使用ByteBuffer存储 以小端格式 |
| XXBufferU/XXBufferS | 内存是否页对齐 区分大小端格式 |
参考:
https://www.jianshu.com/p/1ae227e6af61
1.2、主要参数
| 参数 | 说明 |
|---|---|
| capacity | 内存的容量 |
| position | 读写操作的位置索引(自动更新) |
| limit | 剩余可读/写的上限 |
| mark | 临时存放position的位置 如果比position大 则丢弃 使用reset()恢复 |
| clear() | 清空缓冲区 |
| flip() | 缓冲区转换为读模式 |
| rewind() | 重置position为0 |
| mark()/ reset() | |
| wrap() | 将数组封装为Buffer |
0 <= mark <= position <= limit <= capacity
2、Channel
持有文件描述符 根据具体平台 实现具体的网络、文件native层的操作
3、Selector
selector操作epoll_create/epoll_select方法
4、SelectionKey
- 一个抽象类,表示selectableChannel在Selector中注册的标识.每个Channel向Selector注册时,都将会创建一个selectionKey
- 选择键将Channel与Selector建立了关系,并维护了channel事件.
- 可以通过cancel方法取消键,取消的键不会立即从selector中移除,而是添加到cancelledKeys中,在下一次select操作时移除它.所以在调用某个key时,需要使用isValid进行校验.
SelectionKey.attach可以存储一个对象 在就绪返回时使用
判断事件是否就绪也可以通过boolean selectionKey.isAcceptable()
https://www.jianshu.com/p/d33f2f6cdba0?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
5、Scatter/Gather
Gather:从多个缓冲区将数据按顺序发送到通道中
Scatter:将多个通道中的数据按顺序写到一个缓冲区中
6、Pipe
一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取
类似Linux中进程间的管道 nio中的Pipe用于线程间的数据传输
在单个线程中读写 会造成死锁
三、源码分析
https://segmentfault.com/a/1190000017798684?utm_source=tag-newest
Linux平台的nio基于epoll
channel持有文件描述符
selector操作epoll_create/epoll_select方法 通过SelectionKey获取相关文件描述符的读写标记进行相应操作
四、demo
server
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
/**
* server端实例代码
*
* @author yihonglei
*/
public class NIOServer {
// 通道管理器(Selector)
private static Selector selector;
public static void main(String[] args) throws IOException {
// 创建通道管理器(Selector)
selector = Selector.open();
// 创建通道ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 将通道设置为非阻塞
serverSocketChannel.configureBlocking(false);
// 将ServerSocketChannel对应的ServerSocket绑定到指定端口(port)
ServerSocket serverSocket = serverSocketChannel.socket();
serverSocket.bind(new InetSocketAddress(8989));
/**
* 将通道(Channel)注册到通道管理器(Selector),并为该通道注册selectionKey.OP_ACCEPT事件
* 注册该事件后,当事件到达的时候,selector.select()会返回,
* 如果事件没有到达selector.select()会一直阻塞。
*/
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 循环处理
while (true) {
// 当注册事件到达时,方法返回,否则该方法会一直阻塞
selector.select();
// 获取监听事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
// 迭代处理
while (iterator.hasNext()) {
// 获取事件
SelectionKey key = iterator.next();
// 移除事件,避免重复处理
iterator.remove();
// 检查是否是一个就绪的可以被接受的客户端请求连接
if (key.isAcceptable()) {
handleAccept(key);
} else if (key.isReadable()) {// 检查套接字是否已经准备好读数据
handleRead(key);
}
}
}
}
/**
* 处理客户端连接成功事件
*/
private static void handleAccept(SelectionKey key) throws IOException {
// 获取客户端连接通道
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = server.accept();
socketChannel.configureBlocking(false);
// 信息通过通道发送给客户端
String msg = "Hello Client!";
socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
// 给通道设置读事件,客户端监听到读事件后,进行读取操作
socketChannel.register(selector, SelectionKey.OP_READ);
}
/**
* 监听到读事件,读取客户端发送过来的消息
*/
private static void handleRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
// 从通道读取数据到缓冲区
ByteBuffer buffer = ByteBuffer.allocate(128);
channel.read(buffer);
// 输出客户端发送过来的消息
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("server received msg from client:" + msg);
}
}
client
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.SocketChannel;
import java.util.Iterator;
import java.util.Set;
/**
* client实例代码
*
* @author yihonglei
*/
public class NIOClient {
// 通道管理器(Selector)
private static Selector selector;
public static void main(String[] args) throws IOException {
// 创建通道管理器(Selector)
selector = Selector.open();
// 创建通道SocketChannel
SocketChannel channel = SocketChannel.open();
// 将通道设置为非阻塞
channel.configureBlocking(false);
// 客户端连接服务器,其实方法执行并没有实现连接,需要在handleConnect方法中调channel.finishConnect()才能完成连接
channel.connect(new InetSocketAddress("localhost", 8989));
/**
* 将通道(Channel)注册到通道管理器(Selector),并为该通道注册selectionKey.OP_CONNECT
* 注册该事件后,当事件到达的时候,selector.select()会返回,
* 如果事件没有到达selector.select()会一直阻塞。
*/
channel.register(selector, SelectionKey.OP_CONNECT);
// 循环处理
while (true) {
/*
* 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
* selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
* 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时。
*/
selector.select();
// 获取监听事件
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
// 迭代处理
while (iterator.hasNext()) {
// 获取事件
SelectionKey key = iterator.next();
// 移除事件,避免重复处理
iterator.remove();
// 检查是否是一个就绪的已经连接服务端成功事件
if (key.isConnectable()) {
handleConnect(key);
} else if (key.isReadable()) {// 检查套接字是否已经准备好读数据
handleRead(key);
}
}
}
}
/**
* 处理客户端连接服务端成功事件
*/
private static void handleConnect(SelectionKey key) throws IOException {
// 获取与服务端建立连接的通道
SocketChannel channel = (SocketChannel) key.channel();
if (channel.isConnectionPending()) {
// channel.finishConnect()才能完成连接
channel.finishConnect();
}
channel.configureBlocking(false);
// 数据写入通道
String msg = "Hello Server!";
channel.write(ByteBuffer.wrap(msg.getBytes()));
// 通道注册到选择器,并且这个通道只对读事件感兴趣
channel.register(selector, SelectionKey.OP_READ);
}
/**
* 监听到读事件,读取客户端发送过来的消息
*/
private static void handleRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
// 从通道读取数据到缓冲区
ByteBuffer buffer = ByteBuffer.allocate(128);
channel.read(buffer);
// 输出服务端响应发送过来的消息
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("client received msg from server:" + msg);
}
}
参考:
https://blog.youkuaiyun.com/yhl_jxy/article/details/79335692
超赞:https://segmentfault.com/a/1190000017798684?utm_source=tag-newest
https://www.jianshu.com/c/dfa503d2feac
https://www.cnblogs.com/brandonli/tag/netty/
本文深入解析Java NIO的核心概念,包括Buffer、Channel、Selector等组件的工作原理及应用场景,并通过实战案例展示NIO在服务器端与客户端的具体实现。
3099

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



