一、简介
1. Netty 的介绍
- Netty 是由 JBOSS 提供的一个 Java 开源框架,现为 Github 上的独立项目。
- Netty 是一个异步的、基于事件驱动的网络应用框架,用以快速开发高性能、高可靠性的网络 IO 程序。
- Netty 主要针对在 TCP 协议下,面向 Clients 端的高并发应用,或者 Peer-to-Peer 场景下的大量数据持续传输的 应用。
- Netty 本质是一个
NIO
框架,适用于服务器通讯相关的多种应用场景
2. Netty 的应用场景
-
互联网行业:在分布式系统中,各个节点之间需要远程服务调用,高性能的 RPC 框架必不可少,Netty 作为异步高性能的通信框架,往往作为基础通信组件被这些 RPC 框架使用。
典型的应用有:阿里分布式服务框架
Dubbo
的 RPC 框架使用 Dubbo 协议进行节点间通信,Dubbo 协议默认使用 Netty 作为基础通信组件,用于实现各进程节点之间的内部通信 -
大数据领域:经典的 Hadoop 的高性能通信和序列化组件
Avro
的 RPC 框架,默认采用 Netty 进行跨界点通信;它的 Netty Service 基于 Netty 框架二次封装实现。 -
游戏行业:Netty 作为高性能的基础通信组件,提供了 TCP/UDP 和 HTTP 协议栈,方便定制和开发私有协议栈,账号登录服务器;地图服务器之间可以方便的通过 Netty 进行高性能的通信
BIO编程
1. I/O 模型基本说明
I/O 模型简单的理解:就是用什么样的通道进行数据的发送和接收,很大程度上决定了程序通信的性能
Java 共支持 3 种网络编程模型 I/O 模式:BIO、NIO、AIO
(1)BIO
同步并阻塞(传统阻塞型),服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销
BIO 方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4 以前的唯一选择,但程序简单易理解。
(2)NIO
同步非阻塞,服务器实现模式为一个线程处理多个请求(连接),即客户端发送的连接请求都会注 册到多路复用器上,多路复用器轮询到连接有 I/O 请求就进行处理 NIO 方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,弹幕系统,服务器间通讯等。编程比较复杂,JDK1.4 开始支持。
(3)AIO
异步非阻塞,AIO 引入异步通道的概念,采用了 Proactor 模式,简化了程序编写,有效 的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较 多且连接时间较长的应用
AIO 方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用 OS 参与并发操作, 编程比较复杂,JDK7 开始支持。
2. BIO基本介绍
BIO(blocking I/O):同步阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需 要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,可以通过线程池机制改善(实现多个客户连接服务器)。
Java BIO 就是传统的 java io 编程,其相关的类和接口在 java.io
3. BIO应用实例
- 服务器端启动一个ServerSocket
- 客户端启动 Socket 对服务器进行通信,默认情况下服务器端需要对每个客户建立一个线程与之通讯
- 客户端发出请求后, 先咨询服务器是否有线程响应,如果没有则会等待,或者被拒绝
- 如果有响应,客户端线程会等待请求结束后,再继续执行
(1)服务器端启动一个ServerSocket
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BIOServer {
public static void main(String[] args) throws IOException {
//1. 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//2. 监听6666端口,如果有客户端连接,就创建一个线程,与之通信
ServerSocket serverSocket = new ServerSocket(6666);
System.out.println("服务器启动了");
while (true) {
//阻塞等待客户端连接
Socket socket = serverSocket.accept();
System.out.println("连接到一个客户端");
pool.execute(() -> handler(socket));
}
}
public static void handler(Socket socket) {
byte[] bytes = new byte[1024];
try {
InputStream is = socket.getInputStream();
int len = 0;
//阻塞等待客户端发送数据
while ((len = is.read(bytes)) != -1){
System.out.println(new String(bytes, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println("关闭socket");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(2)客户端与之通讯
-
使用 Socket 进行连接
public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 6666); socket.getOutputStream().write("abc".getBytes()); }
-
使用
telnet
命令模拟客户端与服务端建立连接
telnet localhost 6666
当多个客户端(telnet)与服务端进行连接时,如果超过线程池最大线程数,则后面的请求就只能进阻塞队列,无法被处理。 服务端打印:
当关闭第一个 telnet 客户端时,才会打印:
4. Java BIO 问题分析
- 每个请求都需要创建独立的线程,与对应的客户端进行数据 Read、业务处理以及数据 Write 。
- 当并发数较大时,需要创建大量线程来处理连接,系统资源占用较大。
- 连接建立后,如果当前线程暂时没有数据可读,则线程就阻塞在 Read 操作上,造成线程资源浪费
NIO编程
NIO
全称 non-blocking IO
,是指 JDK 提供的新 API。从 JDK1.4 开始,Java 提供了一系列改进的输入/输出的新特性,被统称为 NIO,是同步非阻塞的
-
NIO 相关类都被放在
java.nio
包及子包下,并且对原java.io
包中的很多类进行改写。 -
NIO 有三大核心部分:
Channel
(通道),Buffer
(缓冲区),Selector
(选择器) -
NIO 是面向缓冲区 ,或者面向块编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后 移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络
-
NIO 的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可 以继续做其他的事情。 非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入, 这个线程同时可以去做别的事情。
-
通俗理解:NIO是可以做到用一个线程来处理多个操作的。HTTP2.0 使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数量比 HTTP1.1 大了好几个数量级
1. Selector、Channel 和 Buffer 的关系
- 每个
Channel
都会对应一个Buffer
Selector
对应一个线程, 一个Selector
对应多个Channel
- 该图反应了有三个
Channel
注册到该Selector
程序 - 程序切换到哪个
Channel
是有事件决定的,Event
就是一个重要的概念 Selector
会根据不同的事件,在各个通道上切换Buffer
就是一个内存块 , 底层是有一个==数组==- 数据的读取写入是通过
Buffer
,Buffer
可以读也可以写(需要通过方法切换)(BIO中要么是输入流,或者是输出流, 不能双向) Channel
也是双向的,可以返回底层操作系统的情况, 比如 Linux , 底层的操作系统通道就是双向的.
2. 缓冲区(Buffer)
缓冲区(Buffer
):缓冲区本质上是一个可以读写数据的内存块,可以理解成是一个容器对象(含数组),该对象提供了一组方法,可以更轻松地使用内存块,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer。
(1)Buffer 类及其子类
在 NIO 中,Buffer
是一个顶层父类,它是一个抽象类。它是非线程安全的
a. 基本属性
Buffer 类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息:
属性 | 描述 | 默认值 |
---|---|---|
mark | 标记。在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置(rewind 和 flip 都会清除 mark 位置) | -1 |
position | 位置。下一个要被读或写的元素的索引,每次读写缓冲区数据时都会改变该值,为下次读写作准备 | 0 |
limit | 表示缓冲区的当前终点,不能对缓冲区超过极限的位置进行读写操作。且极限是可以修改的 | |
capacity | 容量,即可以容纳的最大数据量;在缓冲区创建时被设定并且不能改变 |
b. 基本方法
方法 | 描述 |
---|---|
int capacity() | 返回此缓冲区的容量 |
int position() | 返回此缓冲区的位置 |
Buffer position(int newPosition) | 设置这个缓冲区的位置 |
int limit() | 返回此缓冲区的限制 |
Buffer limit(int newLimit) | 设置此缓冲区的限制 |
Buffer mark() | 将此缓冲区的标记(mark)设置在当前位置(position) |
Buffer reset() | 将此缓冲区的位置(position)重置为先前标记(mark)的位置 |
Buffer clear() | 清除此缓冲区 |
Buffer flip() | 翻转这个缓冲区 |
Buffer rewind() | 倒带这个缓冲区,position设置为零,mark被丢弃 |
int remaining() | 返回当前位置和限制之间的元素数 |
boolean hasRemaining() | 告诉当前位置和极限之间是否存在任何元素 |
abstract boolean isReadOnly() | 告知这个缓冲区是否是只读的 |
abstract boolean hasArray() | 告诉这个缓冲区是否由可访问的数组支持 |
abstract Object array() | 返回支持此缓冲区的数组 (可选操作) |
abstract int arrayOffset() | 返回该缓冲区的缓冲区的第一个元素的背衬数组中的偏移量 (可选操作) |
abstract boolean isDirect() | 告诉这个缓冲区是否为 direct |
c. 子类
Java 中的基本数据类型(boolean
除外),都有一个 Buffer
类型与之相对应。
子类 | 描述 |
---|---|
ByteBuffer | 存储字节数据到缓冲区 |
CharBuffer | 存储字符数据到缓冲区 |
DoubleBuffer | 存储Double数据到缓冲区 |
FloatBuffer | 存储Float数据到缓冲区 |
IntBuffer | 存储Int数据到缓冲区 |
LongBuffer | 存储Long数据到缓冲区 |
ShortBuffer | 存储Short数据到缓冲区 |
(2)ByteBuffer 主要方法
可以在 JDK8 API 中查看所有方法:www.matools.com/api/java8
Java 中的基本数据类型(boolean
除外),都有一个 Buffer 类型与之相对应,最常用的自然是 ByteBuffer
类(二进制数据),该类的主要方法如下:
缓冲区创建相关API:
方法 | 描述 |
---|---|
static ByteBuffer allocate(int capacity) | 设置缓冲区的初始容量 |
static ByteBuffer allocateDirect(int capacity) | 创建新的直接字节缓冲区 |
static ByteBuffer wrap(byte[] array) | 将一个字节数组包装到缓冲区中 |
static ByteBuffer wrap(byte[] array, int offset, int length) | 将一个字节数组包装到缓冲区中,并指定初始化位置offset和上界length |
缓冲区存取相关API:
方法 | 描述 |
---|---|
abstract byte get() | 从当前位置position上get,get之后,position自动+1 |
abstract byte get(int index) | 从绝对位置get |
abstract ByteBuffer put(byte b) | 在当前位置上添加,put之后,position自动+1 |
abstract ByteBuffer put(int index, byte b) | 在绝对位置上put |
abstract ByteBuffer compact() | 压缩此缓冲区 |
(3)ByteBuffer 使用步骤
a. 步骤说明
- 向 buffer 写入数据,例如调用 buffer.put()
- 调用 flip() 切换至读模式
- 从 buffer 读取数据,例如调用 buffer.get()
- 调用 clear() 或 compact() 切换至写模式
- 重复 1~4 步骤
一开始
写模式下,position
是写入位置,limit
等于容量,下图表示写入了 4 个字节后的状态
flip
动作发生后,position
切换为读取位置,limit
切换为读取限制
读取 4 个字节后,状态
clear
动作发生后,状态
compact
方法,是把读完的部分删除,没有读完的部分向前压缩,然后切换至写模式
b. 简单进行存储与读取
public static void main(String[] args) {
//创建容量为5的字节缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
for (int i = 0; i < 5; i++) {
//存入数据
byteBuffer.put(String.valueOf(i).getBytes());
}
//读写切换
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
//调用get时,会使指针位置(position)后移一位
System.out.println((char)byteBuffer.get());
}
}
c. 字符串与 ByteBuffer 互转
//1. 字符串转换为ByteBuffer
ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("你好");
ByteBuffer buffer2 = Charset.forName("utf-8").encode("你好");
//2. ByteBuffer转换为字符串
System.out.println(new String(buffer1.array()));
CharBuffer buffer3 = StandardCharsets.UTF_8.decode(buffer1);
System.out.println(buffer3.getClass());
System.out.println(buffer3.toString());
d. 类型化的put()/get()
public static void main(String[] args) throws IOException {
//创建一个 Buffer
ByteBuffer buffer = ByteBuffer.allocate(64);
//类型化方式放入数据
buffer.putInt(100);
buffer.putChar('牛');
//取出
buffer.flip();
//要按放入方式取出,否则会抛BufferUnderflowException
System.out.println(buffer.getInt());
System.out.println(buffer.getLong());
}
e. 只读类型Buffer
ByteBuffer buffer = ByteBuffer.allocate(64);
//转换成只读类型Buffer
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
readOnlyBuffer.put((byte)100); //抛ReadOnlyBufferException
3. 通道(Channel)
- NIO 的通道类似于流,但有些区别如下:
- 通道可以同时进行读写,而流只能读或者只能写
- 通道可以实现异步读写数据
- 通道可以从缓冲读数据,也可以写数据到缓冲
- BIO 中的 stream 是单向的,例如
FileInputStream
对象只能进行读取数据的操作,而 NIO 中的通道(Channel) 是==双向的==,可以读操作,也可以写操作。 - Channel 在 NIO 中是一个接口
public interface Channel extends Closeable{}
- ==常用的 Channel 实现类有 :==
FileChannel
用于文件的数据读写DatagramChannel
用于 UDP 的数据读写ServerSocketChannel
和SocketChannel
用于 TCP 的数据读写。【ServerSocketChanne 类似 ServerSocket,SocketChannel 类似 Socket】
(1)FileChannel(文件的读写)
a. 常用方法
FileChannel
只能工作在==阻塞模式==下,主要用来对本地文件进行 IO 操作,常见的方法有
方法 | 描述 |
---|---|
abstract int read(ByteBuffer dst) | 从通道读取数据并放到缓冲区中,返回值表示读到了多少字节,-1 表示到达了文件的末尾 |
abstract int write(ByteBuffer src) | 把缓冲区的数据写到通道中 |
abstract long transferFrom(ReadableByteChannel src, long position, long count) | 从目标通道中复制数据到当前通道 |
abstract long transferTo(long position, long count, WritableByteChannel target) | 把数据从当前通道复制给目标通道 |
abstract void force(boolean metaData) | 强制将文件内容和元数据(文件的权限等信息)立刻写入磁盘 (操作系统出于性能的考虑,会将数据缓存,不是立刻写入磁盘) |
abstract long size() | 获取此通道文件的大小 |
abstract long position() | 获取当前位置 |
abstract FileChannel position(long newPosition) | 设置当前位置 |
void close() | 关闭Channel。Channel 必须关闭,不过调用了 FileInputStream、FileOutputStream 或者 RandomAccessFile 的 close 方法会间接地调用 channel 的 close 方法 |
b. 读取/写入文件
- 不能直接打开
FileChannel
,必须通过FileInputStream
、FileOutputStream
或者RandomAccessFile
来获取FileChannel
,它们都有getChannel
方法
- 通过
FileInputStream
获取的channel
只能读 - 通过
FileOutputStream
获取的channel
只能写 - 通过
RandomAccessFile
是否能读写根据构造RandomAccessFile
时的读写模式决定
案例1,将文件1通过 Channel 读到 Buffer 中,再从 Buffer 经过 Channel 写入到文件2中
private static void readToBufferToWriteFile() throws IOException {
//创建一个ByteBuffer
ByteBuffer byteBuffer = ByteBuffer.allocate(2);
//获取1.txt文件的输入流及FileChannel
FileInputStream fileInputStream = new FileInputStream("1.txt");
FileChannel inputChannel = fileInputStream.getChannel();
//获取2.txt文件的输出流及FileChannel
FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
FileChannel outputChannel = fileOutputStream.getChannel();
//从FileChannel中读取数据,直到读完(返回-1)
while (inputChannel.read(byteBuffer) != -1) {
//打印一下,可能会乱码,不影响结果
System.out.print(new String(byteBuffer.array()));
//切换
byteBuffer.flip();
//将ByteBuffer中的数据写入到FileChannel
outputChannel.write(byteBuffer);
//清空ByteBuffer,否则inputChannel.read(byteBuffer)会始终返回0,导致循环写入2.txt
byteBuffer.clear();
}
//关闭流
fileInputStream.close();
fileOutputStream.close();
}
案例2,将文件1经过 Channel1 直接拷贝到 Channel2
private static void directReadToWrite() throws IOException {
FileInputStream fileInputStream = new FileInputStream("1.txt");
FileChannel channel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
FileChannel channel1 = fileOutputStream.getChannel();
//使用 transferFrom 和 transferTo 都可以
// channel1.transferFrom(channel, 0, channel.size());
channel.transferTo(0, channel.size(), channel1);
fileInputStream.close();
fileOutputStream.close();
}
transferTo
方法一次性最多传输 2G
的数据,当文件大于 2G
时,需要循环拷贝:
//超过2G大小文件的拷贝
public static void testFileChannelTransferTo() {
try (
FileChannel from = new FileInputStream("data.txt").getChannel();
FileChannel to = new FileOutputStream("to.txt").getChannel();
) {
// 效率高,底层会利用操作系统的零拷贝进行优化
long size = from.size();
// left 变量代表还剩余多少字节
for (long left = size; left > 0; ) {
System.out.println("position:" + (size - left) + " left:" + left);
left -= from.transferTo((size - left), left, to);
}
} catch (IOException e) {
e.printStackTrace();
}
}
案例3,使用 MappedByteBuffer,让文件直接在内存(堆外的内存)中进行修改
MappedByteBuffer
可让文件直接在内存(堆外内存)修改,操作系统不需要拷贝一次
public static void main(String[] args) throws IOException {
/*
* 参数1:文件名
* 参数2:模式,r,rw,rws,rwd
*/
RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt", "rw"); //获取对应的通道
FileChannel channel = randomAccessFile.getChannel();
/*
* 参数 1: FileChannel.MapMode.READ_WRITE 使用的读写模式
* 参数 2: 0: 可以直接修改的起始位置
* 参数 3: 5: 是映射到内存的大小(不是索引位置) ,即将 1.txt 的多少个字节映射到内存
* 可以直接修改的范围就是 [0, 5)
* 实际类型 DirectByteBuffer
*/
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0, (byte) 'H');
mappedByteBuffer.put(3, (byte) '9');
randomAccessFile.close();
}
案例4,使用多个Buffer(即 Buffer 数组) 完成读写操作(Scattering 和 Gathering)
Scattering
:将数据写入到 Buffer 时,可以采用 Buffer 数组,依次写入 [分散]
Gathering
:从 Buffer 读取数据时,可以采用 Buffer 数组,依次读取
public static void main(String[] args) {
try (
FileChannel inputChannel = new FileInputStream("1.txt").getChannel();
FileChannel outputChannel = new FileOutputStream("2.txt").getChannel();
) {
ByteBuffer buffer1 = ByteBuffer.allocate(2);
ByteBuffer buffer2 = ByteBuffer.allocate(5);
ByteBuffer[] byteBuffers = {buffer1, buffer2};
//Scattering
while (inputChannel.read(byteBuffers) != -1) {
//对数组中每一个Buffer执行flip操作
Arrays.stream(byteBuffers).forEach(ByteBuffer::flip);
//Gathering
outputChannel.write(byteBuffers);
Arrays.stream(byteBuffers).forEach(ByteBuffer::clear);
}
} catch (IOException e) {
e.printStackTrace();
}
}
(2)SocketChannel
SocketChannel
,网络 IO 通道,具体负责进行读写操作。NIO 把缓冲区的数据写入通道,或者把通道里的数据读到缓冲区。
a. 常用方法
方法 | 描述 |
---|---|
static SocketChannel open() | 打开通道,得到一个 SocketChannel 通道 |
SelectableChannel configureBlocking(boolean block) | 设置通道是阻塞还是非阻塞的,false 表示非阻塞模式 |
abstract boolean connect(SocketAddress remote) | 连接服务器 |
abstract boolean finishConnect() | 如果上面的方法连接失败,接下来就要通过该方法完成连接操作 |
abstract int write(ByteBuffer src) | 从 Buffer 往通道里写数据 |
long write(ByteBuffer[] srcs) | 从 Buffer 数组中往通道里写数据 |
abstract int read(ByteBuffer dst) | 从通道读取数据到 Buffer 中 |
long read(ByteBuffer[] dsts) | 从通道读取数据到 Buffer 数组中 |
SelectionKey register(Selector sel, int ops, Object att) | 注册一个选择器并设置监听事件(第二个参数),最后一个参数可以设置共享数据(可以不指定) |
void close() | 关闭通道 |
(3)ServerSocketChannel
ServerSocketChannel
在服务器端监听新的客户端 Socket
连接
a. 常用方法
方法 | 描述 |
---|---|
static ServerSocketChannel open() | 打开服务器通道,得到一个 ServerSocketChannel |
ServerSocketChannel bind(SocketAddress local) | 设置服务器端端口号 |
SelectableChannel configureBlocking(boolean block) | 设置通道是阻塞还是非阻塞的,false 表示非阻塞模式 |
abstract SocketChannel accept() | 接受一个连接,返回代表这个连接的通道对象null |
SelectionKey register(Selector sel, int ops) | 注册一个选择器,并设置监听事件(详见SelectionKey) |
void close() | 关闭通道 |
b. 案例,使用ServerSocketChannel与SocketChannel实现数据收发(BIO)
ServerSocketChannel
实现监听请求,ServerSocketChannel
阻塞模式时使用和ServerSocket
逻辑相同,即BIO
(NIO 需要用到 Selector,后面会说)。public static void main(String[] args) { try ( ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); ) { //监听6666端口 serverSocketChannel.bind(new InetSocketAddress(6666)); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); //等待请求,阻塞;可以设置通道为非阻塞的,没有连接会返回null SocketChannel socketChannel = serverSocketChannel.accept(); while (socketChannel.read(byteBuffer) != -1) { System.out.println(new String(byteBuffer.array())); byteBuffer.clear(); } } catch (IOException e) { e.printStackTrace(); } }
- 使用
SocketChannel
向服务端发送数据public static void main(String[] args) { try ( SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 6666)); ) { socketChannel.write(ByteBuffer.wrap("Hello World!".getBytes())); } catch (IOException e) { e.printStackTrace(); } }
4. Selector(选择器)
- Java 的 NIO,用非阻塞的 IO 方式。可以用一个线程,处理多个的客户端连接,就会使用到 Selector(选择器)
- Selector 能够检测多个注册的通道上是否有==事件==发生(注意:多个 Channel 以事件的方式可以注册到同一个 Selector),如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求。
- 只有在连接的通道真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程
- 避免了多线程之间的上下文切换导致的开销
(1)Selector 常用方法
方法 | 描述 |
---|---|
static Selector open() | 得到一个选择器对象 |
abstract int select() | 监控所有注册到Selector上的通道,当其中有IO操作可以进行时,将对应的 SelectionKey 加入到内部集合中,并返回事件发生的通道个数,该方法是阻塞的 |
abstract int select(long timeout) | 同 select(),参数用来设置超时时间 |
abstract int selectNow() | 立即返回,非阻塞的,如果没有可选择的通道则返回0 |
abstract Set<SelectionKey> keys() | 从内部集合中得到所有的 SelectionKey |
abstract Set<SelectionKey> selectedKeys() | 从内部集合中得到所有发生事件了的 SelectionKey |
abstract Selector wakeup() | 唤醒select() |
abstract void close() | 关闭选择器 |
(2)SelectionKey常量及方法
SelectionKey
中使用常量表示 Selector 和网络通道的注册关系,共四种:
OP_ACCEPT
:有新的网络连接可以 accept,值为 16OP_CONNECT
:代表连接已经建立,值为 8OP_READ
:读操作,值为 1OP_WRITE
:写操作,值为 4
常用方法:
方法 | 描述 |
---|---|
abstract Selector selector() | 得到与之关联的Selector对象 |
abstract SelectableChannel channel() | 得到与之关联的Channel对象 |
Object attachment() | 得到与之关联的共享数据 |
abstract int interestOps() | 设置或改变监听事件 |
boolean isAcceptable() | 是否可以accept |
boolean isReadable() | 是否可以读 |
boolean isWritable() | 是否可以写 |
(3)NIO 非阻塞网络编程原理分析图
对上图的说明:
- 当客户端连接时,会通过
ServerSocketChannel
得到SocketChannel
Selector
进行监听select
方法, 返回有事件发生的通道的个数.- 将
socketChannel
注册到Selector
上,register(Selectorsel,intops)
,一个selector
上可以注册多个SocketChannel
- 注册后返回一个
SelectionKey
, 会和该Selector
关联(集合) - 进一步得到各个
SelectionKey
(有事件发生) - 在通过
SelectionKey
反向获取SocketChannel
, 方法channel()
- 可以通过得到的
channel
, 完成业务处理
(4)案例1,服务器端和客户端之间的数据简单通讯(NIO)
- 服务端,监听 6666 端口
private static void NIOServerSocketChannelSelfTest() {
try (
//创建 ServerSocketChannel -> ServerSocket
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//得到一个 Selecor 对象
Selector selector = Selector.open();
) {
//配置非阻塞
serverSocketChannel.configureBlocking(false);
//绑定一个端口 6666, 在服务器端监听
serverSocketChannel.bind(new InetSocketAddress(6666));
//把 serverSocketChannel 注册到 selector, 事件为 OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//循环等待客户端连接
while (true) {
//如果返回的>0, 说明有通道发生事件
int select = selector.select(5000);
if (select > 0) {
// 返回发生事件的Set
Set<SelectionKey> selectionKeys = selector.selectedKeys();
//遍历 Set<SelectionKey>, 使用迭代器遍历
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
//获取到 SelectionKey
SelectionKey key = iterator.next();
key.cancel();
//根据 key 对应的通道发生的事件做相应处理
if (key.isAcceptable()) {
System.out.println("有可新连接的管道");
//获取新连接的SocketChannel是阻塞的
SocketChannel accept = serverSocketChannel.accept();
//配置非阻塞
accept.configureBlocking(false);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//将 socketChannel 注册到 selector, 关注事件为 OP_READ, 同时给 socketChannel
accept.register(selector, SelectionKey.OP_READ, byteBuffer);
} else if (key.isReadable()) {
System.out.println("发生读事件");
//通过 key 反向获取到对应 channel
SocketChannel channel = (SocketChannel) key.channel();
//获取到该 channel 关联的 buffer
ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
//如果一次没读完,会再次产生读事件,循环直到读完
int read = channel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
byteBuffer.clear();
}
//处理完毕,必须将事件移除
iterator.remove();
}
} else {
System.out.println("等待了5s,无连接");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
- 客户端,连接 6666 端口
private static void NIOSocketChannelSelfTest() {
try (
//得到一个网络通道
SocketChannel socketChannel = SocketChannel.open();
) {
//设置非阻塞
socketChannel.configureBlocking(false);
//提供服务器端的 ip 和 端口
InetSocketAddress address = new InetSocketAddress("localhost", 6666);
if (!socketChannel.connect(address)) {
while (!socketChannel.finishConnect()) {
System.out.println("因为连接需要时间,客户端不会阻塞,可以做其它工作");
}
}
System.out.println(socketChannel.isConnected());
//如果连接成功,发送数据
ByteBuffer byteBuffer = ByteBuffer.wrap("Hello World!".getBytes());
socketChannel.write(byteBuffer);
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
(5)案例2,使用NIO实现一个简单的群聊系统
- 一个 Client 给 Server 发送消息,Server 将消息转发给其它 Client
服务端:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class GroupChatServer {
private Selector selector;
private ServerSocketChannel listenChannel;
public static final int PORT = 6666;
//构造器,初始化工作
public GroupChatServer() {
try {
//得到选择器
selector = Selector.open();
//ServerSocketChannel
listenChannel = ServerSocketChannel.open();
//绑定端口
listenChannel.bind(new InetSocketAddress(PORT));
//设置非阻塞模式
listenChannel.configureBlocking(false);
//将该 listenChannel 注册到 selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
//监听
public void listen() {
try {
//循环处理
while (true) {
int count = selector.select(5000);
if (count > 0) {//有事件处理
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
//监听到 accept 事件
if (key.isAcceptable()) {
SocketChannel sc = listenChannel.accept();
sc.configureBlocking(false);
//将该 sc 注册到 seletor
sc.register(selector, SelectionKey.OP_READ);
//提示
System.out.println(sc.getRemoteAddress() + " 上线了");
} else if (key.isReadable()) {//通道发送 read 事件
//处理读
readData(key);
}
//当前的 key 删除,防止重复处理
iterator.remove();
}
} else {
System.out.println("等待...");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void readData(SelectionKey key) {
//取到关联的 channle
SocketChannel channel = null;
try {
//得到 channel
channel = (SocketChannel) key.channel();
//创建 buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
int count = channel.read(buffer);
if (count > 0) {
//把缓存区的数据转成字符串
String msg = new String(buffer.array());
//输出该消息
System.out.println("form 客户端:" + msg);
//向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
sendInfoToOtherClients(msg, channel);
}
} catch (IOException e) {
// e.printStackTrace();
try {
System.out.println(channel.getRemoteAddress() + " 离线了...");
//取消注册
key.cancel();
//关闭通道
channel.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
//转发消息给其它客户(通道)
private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
System.out.println("服务器转发消息中");
//遍历所有注册到 selector 上的 SocketChannel,并排除自己
for (SelectionKey key : selector.keys()) {
SelectableChannel channel = key.channel();
if (channel instanceof SocketChannel && !channel.equals(self)) {
SocketChannel dest = (SocketChannel) channel;
//将 msg 存储到 buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//将 buffer 的数据写入 通道
dest.write(buffer);
}
}
}
public static void main(String[] args) {
GroupChatServer chatServer = new GroupChatServer();
chatServer.listen();
}
}
客户端:
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.Scanner;
/**
* @author Zyx
* @since 2021/8/9 11:36 上午
*/
public class GroupChatClient {
private final String HOST = "localhost";
private final int PORT = 6666;
private Selector selector;
private SocketChannel socketChannel;
private String username;
//构造器, 完成初始化工作
public GroupChatClient() throws IOException {
//获取选择器
selector = Selector.open();
//连接服务器
socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
//设置非阻塞
socketChannel.configureBlocking(false);
//将 channel 注册到 selector
socketChannel.register(selector, SelectionKey.OP_READ);
//得到 username
username = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(username + " is OK!");
}
//向服务器发送消息
public void sendInfo(String info) {
info = username + " 说:" + info;
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
//读取从服务器端回复的消息
public void readInfo() {
try {
int readChannels = selector.select();
if (readChannels > 0) {//有可以用的通道
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
if (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
//得到相关的通道
SocketChannel sc = (SocketChannel) key.channel();
//得到一个 Buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
//读取
sc.read(buffer);
//把读到的缓冲区的数据转成字符串
String msg = new String(buffer.array());
System.out.println(msg.trim());
}
//删除当前的 selectionKey, 防止重复操作
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
//启动客户端
GroupChatClient chatClient = new GroupChatClient();
//每3秒从服务器读取数据
new Thread() {
@Override
public void run() {
while (true) {
chatClient.readInfo();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
//发送数据给服务器端
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
chatClient.sendInfo(s);
}
}
}