文章目录
1. 简介
- Java NIO 全称
java non-blocking IO
,是指 JDK 提供的新 API。从 JDK1.4 开始,Java 提供了一系列改进的 输入/输出的新特性,被统称为 NIO(即 New IO),是同步非阻塞的 。 - NIO 相关类都被放在 java.nio 包及子包下,并且对原 java.io 包中的很多类进行改写。
- NIO 有三大核心部分:
Channel(通道)
,Buffer(缓冲区)
,Selector(选择器)
。 NIO 是 面向缓冲区 ,或者面向 块 编程
的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后 移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络 。- Java NIO 的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果 目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可 以继续做其他的事情。 非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入, 这个线程同时可以去做别的事情。
- 通俗理解:NIO 是可以做到用一个线程来处理多个操作的。假设有 10000 个请求过来,根据实际情况,可以分配 50 或者 100 个线程来处理。不像之前的阻塞 IO 那样,非得分配 10000 个。
- HTTP2.0 使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数量比 HTTP1.1 大了好 几个数量级。
2. NIO 和 BIO 的比较
- BIO 以流的方式处理数据,而 NIO 以块的方式处理数据,块 I/O 的效率比流 I/O 高很多。
- BIO 是阻塞的,NIO 则是非阻塞的 。
- BIO 基于字节流和字符流进行操作,而 NIO 基于 Channel(通道)和 Buffer(缓冲区)进行操作,数据总是从通道 读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择器)用于监听多个通道的事件(比如:连接请求, 数据到达等),因此使用单个线程就可以监听多个客户端通道。
3. NIO 三大核心原理示意图
一张图描述 NIO 的 Selector 、 Channel 和 Buffer 的关系
简单版:
关系图的说明:
- 每个channel 都会对应一个Buffer
- Selector 对应一个线程, 一个线程对应多个channel(连接)
- 该图反应了有三个channel 注册到 该selector //程序
- 程序切换到哪个channel 是有事件决定的, Event 就是一个重要的概念
- Selector 会根据不同的事件,在各个通道上切换
- Buffer 就是一个内存块 , 底层是有一个数组
- 数据的读取写入是通过Buffer, 这个和BIO , BIO 中要么是输入流,或者是
输出流,不能双向,但是NIO的Buffer 是可以读也可以写, 需要 flip 方法切换 - channel 是双向的, 可以返回底层操作系统的情况, 比如Linux , 底层的操作系统
通道就是双向的.
4. 缓冲区(Buffer)
缓冲区(Buffer):缓冲区本质上是一个可以读写数据的内存块
,可以理解成是一个容器对象(含数组)
,该对象提供了一组方法,可以更轻松地使用内存块,,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer
4.1 Buffer 类及其子类
在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类
,
类的层级关系图: idea里面ctrl+H 快捷键可以看
4.2 常用Buffer子类
- ByteBuffer,存储字节数据到缓冲区
- ShortBuffer,存储字符串数据到缓冲区
- CharBuffer,存储字符数据到缓冲区
- IntBuffer,存储整数数据到缓冲区
- LongBuffer,存储长整型数据到缓冲区
- DoubleBuffer,存储小数到缓冲区
- FloatBuffer,存储小数到缓冲区
4.3 Buffer四大属性
Buffer类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息:
- Mark 标记
- Position 位置,下一个要被读或写的元素的索引,每次读写缓冲区数据时都会改变改值,为下次读写作准备
- Limit 表示缓冲区的当前终点,不能对缓冲区超过极限的位置进行读写操作。且极限是可以修改的
- Capacity 容量,即可以容纳的最大数据量;在缓冲区创建时被设定并且不能改变
4.4 Buffer类相关方法
public abstract class Buffer {
//JDK1.4时,引入的api
public final int capacity( )//返回此缓冲区的容量
public final int position( )//返回此缓冲区的位置
public final Buffer position (int newPositio)//设置此缓冲区的位置
public final int limit( )//返回此缓冲区的限制
public final Buffer limit (int newLimit)//设置此缓冲区的限制
public final Buffer mark( )//在此缓冲区的位置设置标记
public final Buffer reset( )//将此缓冲区的位置重置为以前标记的位置
public final Buffer clear( )//清除此缓冲区, 即将各个标记恢复到初始状态,但是数据并没有真正擦除, 后面操作会覆盖
public final Buffer flip( )//反转此缓冲区
public final Buffer rewind( )//重绕此缓冲区
public final int remaining( )//返回当前位置与限制之间的元素数
public final boolean hasRemaining( )//告知在当前位置和限制之间是否有元素
public abstract boolean isReadOnly( );//告知此缓冲区是否为只读缓冲区
//JDK1.6时引入的api
public abstract boolean hasArray();//告知此缓冲区是否具有可访问的底层实现数组
public abstract Object array();//返回此缓冲区的底层实现数组
public abstract int arrayOffset();//返回此缓冲区的底层实现数组中第一个缓冲区元素的偏移量
public abstract boolean isDirect();//告知此缓冲区是否为直接缓冲区
4.4.1 最常用的自然是ByteBuffer 类(二进制数据)
public abstract class ByteBuffer {
//缓冲区创建相关api
public static ByteBuffer allocateDirect(int capacity)//创建直接缓冲区
public static ByteBuffer allocate(int capacity)//设置缓冲区的初始容量
public static ByteBuffer wrap(byte[] array)//把一个数组放到缓冲区中使用
//构造初始化位置offset和上界length的缓冲区
public static ByteBuffer wrap(byte[] array,int offset, int length)
//缓存区存取相关API
public abstract byte get( );//从当前位置position上get,get之后,position会自动+1
public abstract byte get (int index);//从绝对位置get
public abstract ByteBuffer put (byte b);//从当前位置上添加,put之后,position会自动+1
public abstract ByteBuffer put (int index, byte b);//从绝对位置上put
}
4.5 Buffer缓冲区代码演示
import java.nio.ByteBuffer;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/5 21:40
* @description: ByteBuffer和Channel的注意事项和细节
*/
public class BufferUnderflowExceptionDemo {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//类型化方式放入数据
byteBuffer.putInt(100);
byteBuffer.putLong(9L);
byteBuffer.putChar('王');
byteBuffer.putShort((short) 4);
//取出
byteBuffer.flip();
System.out.println(byteBuffer.getShort());
System.out.println(byteBuffer.getChar());
System.out.println(byteBuffer.getLong());
System.out.println(byteBuffer.getLong());
// System.out.println(byteBuffer.getInt());
}
}
注意事项:
- ByteBuffer 支持类型化的put 和 get, put 放入的是什么数据类型,get就应该使用相应的数据类型来取出,否则可能有
BufferUnderflowException
异常。[举例说明]
import java.nio.ByteBuffer;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/5 21:40
* @description:
* ByteBuffer 支持类型化的put 和 get, put 放入的是什么数据类型,
* get就应该使用相应的数据类型来取出,
* 否则可能有 BufferUnderflowException 异常。
*/
public class BufferUnderflowExceptionDemo {
public static void main(String[] args) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//类型化方式放入数据
byteBuffer.putInt(100);
byteBuffer.putLong(9L);
byteBuffer.putChar('王');
byteBuffer.putShort((short) 4);
//取出
byteBuffer.flip();
System.out.println(byteBuffer.getShort());
System.out.println(byteBuffer.getChar());
System.out.println(byteBuffer.getLong());
System.out.println(byteBuffer.getLong());
// System.out.println(byteBuffer.getInt());
}
}
- NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进行修改, 而如何同步到文件由NIO 来完成. 还可以将一个普通Buffer 转成只读Buffer
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/6 15:11
* @description:
* MapperedBuffer支持在内存中(堆外内存)修改,操作系统不需要拷贝一次
*/
public class MapperedBufferDemo {
public static void main(String[] args) throws IOException {
//rw代表读写权限
RandomAccessFile randomAccessFile = new RandomAccessFile("a.txt", "rw");
//获取对应的通道
FileChannel fileChannel = randomAccessFile.getChannel();
/**
* 参数1: FileChannel.MapMode.READ.WRITE 使用的读写模式
* 参数2: 0 :可以直接修改的起始位置
* 参数3: 15: 是映射到内存的大小(并非索引),即将a.txt的多少个字节映射到内存
* 可以直接修改的范围就是0-15
*
*/
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 15);
mappedByteBuffer.put(0, (byte) 'W'); //代表修改第一个字节位置
mappedByteBuffer.put(3, (byte) 'Q'); //代表修改第4个字节位置
//关闭流
randomAccessFile.close();
System.out.println("修改成功");
}
}
- NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进行修改, 而如何同步到文件由NIO 来完成.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/6 16:04
* @description:
* Scattering: 将数据写入到buffer时,可以采用buffer数组,依次写入[分散]
* <p>
* Gathering: 从buffer读取数据时,可以采用buffer数组,依次读
*/
public class ScatteringAndGatheringDemo {
public static void main(String[] args) throws IOException {
//使用 ServerSocketChannel 和 SocketChannel 网络
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//设置输入端口
InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
//绑定端口到socket,并启动
serverSocketChannel.socket().bind(inetSocketAddress);
//创建buffere数组,包含2个bytebuffer数组
ByteBuffer[] byteBuffers = new ByteBuffer[2];
//设置第一个数组装5个字节
byteBuffers[0] = ByteBuffer.allocate(5);
//设置第二个数组装3个字节
byteBuffers[1] = ByteBuffer.allocate(3);
//等客户端连接(telnet)
SocketChannel socketChannel = serverSocketChannel.accept();
//假定从客户端接收8个字节
int messageLenght = 8;
//循环的读
while (true) {
int byteRead = 0;
while (byteRead < messageLenght) {
long l = socketChannel.read(byteBuffers);
//累计读取的字节数
byteRead += l;
System.out.println("byteRead = " + byteRead);
Arrays.asList(byteBuffers).stream().map(c -> "postion=" + c.position() + ", limit" + c.limit()).forEach(System.out::println);
}
//将所有的buffer进行flip
Arrays.asList(byteBuffers).forEach(c->c.flip());
//将数据读出显示在客户端
int byteWrite = 0;
while (byteWrite<messageLenght){
long l = socketChannel.write(byteBuffers);
byteWrite += l;
}
//将所有buffer进行clear
Arrays.asList(byteBuffers).forEach(c -> c.clear());
System.out.println("byteRead:="+byteRead+"byteWrite="+byteWrite+", messagelength"+messageLenght);
}
}
}
5. 通道(Channel)
-
NIO的通道类似于流,但有些区别如下:
1.1 通道可以同时进行读写,而流只能读或者只能写
1.2. 通道可以实现异步读写数据
1.3. 通道可以从缓冲读数据,也可以写数据到缓冲:
-
BIO 中的 stream 是单向的,例如 FileInputStream 对象只能进行读取数据的操作,
而 NIO 中的通道(Channel)是双向的,可以读操作,也可以写操作。 -
Channel 在 NIO 中是一个接口
-
常 用 的 Channel 类 有 : FileChannel 、 DatagramChannel 、 ServerSocketChannel 和 SocketChannel【ServerSocketChanne 类似 ServerSocket , SocketChannel 类似 Socket】
-
FileChannel 用于文件的数据读写,DatagramChannel 用于 UDP 的数据读写,ServerSocketChannel 和 SocketChannel 用于 TCP 的数据读写。
FileChannel 类 FileChannel 主要用来对本地文件进行 IO 操作,常见的方法有
public int read(ByteBuffer dst) //从通道读取数据并放到缓冲区中
public int write(ByteBuffer src) // 把缓冲区的数据写到通道中
public long transferFrom(ReadableByteChannel src, long position, long count)
// 从目标通道中复制数据到当前通道
public long transferTo(long position, long count, WritableByteChannel target)
// 把数据从当前通道复制给目标通道
5.1 应用实例1-本地文件写数据
package com.netty;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/1 23:38
* @description: 应用实列1-往本地文件写数据
*/
public class ChannelDemo1 {
public static void main(String[] args) throws Exception {
String str = "Hello,xxx";
//创建输出流
FileOutputStream outputStream = new FileOutputStream("F:\\a.txt");
//通过fileoutputstream获取对应的filechannel
//这个filechannel真实的类型是filechannelImpl
FileChannel channel = outputStream.getChannel();
//创建一个缓冲区 ByteBuffer
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//将str放入byteBuffer
byteBuffer.put(str.getBytes());
//对byteBuffer 进行flip
byteBuffer.flip();
//将buffer写入通道
channel.write(byteBuffer);
//最后别忘记了关闭流
outputStream.close();
}
}
5.2 应用实例2-本地文件读数据
package com.netty;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/3 21:54
* @description: 将本地的文件读取出来
*/
public class ChannelDemo2 {
public static void main(String[] args) throws Exception {
File file = new File("F:\\a.txt");
//创建文件输入流
FileInputStream inputStream = new FileInputStream(file);
//通过fileinputstream获取对应的filechannel 实际类型为 filechannelImpl
FileChannel fileChannel = inputStream.getChannel();
//创建缓冲区,这里为了避免浪费空间使用文件的长度
ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
//将通道当中的数据写入到Buffer
fileChannel.read(byteBuffer);
//将byteBuffer的字节数据转成String
System.out.println(new String(byteBuffer.array()));
//最后记得关闭流
inputStream.close();
}
}
5.3 应用实例3-使用一个Buffer完成文件读取
package com.netty;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/4 22:03
* @description: 将一个文件拷贝到另外一个地方
*/
public class ChannelDemo3 {
public static void main(String[] args) throws IOException {
//创建输入流
FileInputStream fileInputStream = new FileInputStream("a.txt");
//获取输入流通道
FileChannel fileChannel01 = fileInputStream.getChannel();
//创建输出流
FileOutputStream fileOutputStream = new FileOutputStream("b.txt");
FileChannel fileChannel02 = fileOutputStream.getChannel();
//创建Buffer
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
//清空buffer
byteBuffer.clear();
int read = fileChannel01.read(byteBuffer);
//当read=-1时表示读完
if (read == -1) {
break;
}
//将buffer中的数据写入到fileChannel02中---b.txt
byteBuffer.flip();
fileChannel02.write(byteBuffer);
}
fileOutputStream.close();
fileInputStream.close();
}
}
5.4 应用实例4-拷贝文件transferFrom 方法
package com.netty;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/5 20:39
* @description: 拷贝文件 使用transferFrom
*/
public class ChannelDemo4 {
public static void main(String[] args) throws Exception {
//创建相关流
FileInputStream fileInputStream = new FileInputStream("a.txt");
FileOutputStream fileOutputStream = new FileOutputStream("c.txt");
//获取各个流对应的fileChannel
FileChannel sourceCh = fileInputStream.getChannel();
FileChannel destCh = fileOutputStream.getChannel();
//使用destCh
destCh.transferFrom(sourceCh, 0, sourceCh.size());
//关闭流
sourceCh.close();
destCh.close();
fileInputStream.close();
fileOutputStream.close();
}
}
6. Selector(选择器)
- Java 的 NIO,用非阻塞的 IO 方式。可以用一个线程处理多个的客户端连接,就会使用到 Selector(选择器)
- Selector 能够检测多个注册的通道上是否有事件发生(注意:多个 Channel 以事件的方式可以注册到同一个 Selector),如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管 理多个通道,也就是管理多个连接和请求。
- 只有在 连接/通道 真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都 创建一个线程,不用去维护多个线程 4) 避免了多线程之间的上下文切换导致的开销
Selector示意图和特点说明:
特点再说明:
4. Netty 的 IO 线程 NioEventLoop 聚合了 Selector(选择器,也叫多路复用器),可以同时并发处理成百上千个客户端连接。
5. 当线程从某客户端 Socket 通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。
6. 线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入和输出通道。
7. 由于读写操作都是非阻塞的,这就可以充分提升 IO 线程的运行效率,避免由于频繁 I/O 阻塞导致的线程挂起。
8. 一个 I/O 线程可以并发处理 N 个客户端连接和读写操作,这从根本上解决了传统同步阻塞 I/O 一连接一线程模型,架构的性能、弹性伸缩能力和可靠性都得到了极大的提升。
6.1 Selector 类相关方法
Selector 类是一个抽象类, 常用方法和说明如下:
public abstract class Selector implements Closeable {
public static Selector open();//得到一个选择器对象
public int select(long timeout);//监控所有注册的通道,当其中有 IO 操作可以进行时,将对应的 SelectionKey 加入到内部集合中并返回,参数用来设置超时时间
public Set<SelectionKey> selectedKeys();//从内部集合中得到所有的 SelectionKey
}
注意事项:
NIO中的 ServerSocketChannel功能类似ServerSocket,SocketChannel功能类似Socket
selector 相关方法说明:
selector.select()//阻塞
selector.select(1000);//阻塞1000毫秒,在1000毫秒后返回
selector.wakeup();//唤醒selector
selector.selectNow();//不阻塞,立马返还
7. NIO 非阻塞 网络编程原理分析图
NIO 非阻塞 网络编程相关的(Selector
、SelectionKey
、ServerScoketChannel
和 SocketChannel
) 关系梳理图
对上图的说明:
- 当客户端连接时,会通过 ServerSocketChannel 得到 SocketChannel;
- Selector 进行监听 select 方法, 返回有事件发生的通道的个数;
- 将 socketChannel 注册到 Selector 上, register(Selector sel, int ops), 一个 selector 上可以注册多个 SocketChannel;
- 注册后返回一个 SelectionKey, 会和该 Selector 关联(集合);
- 进一步得到各个 SelectionKey (有事件发生);
- 在通过 SelectionKey 反向获取 SocketChannel , 方法 channel()
- 可以通过 得到的 channel , 完成业务处理
7.1 代码演示
客户端:
package com.netty.NioDemo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/9 21:41
* @description:
*/
public class NIOClient {
public static void main(String[] args) throws Exception {
SocketChannel socketChannel = SocketChannel.open();
//设置为非阻塞
socketChannel.configureBlocking(false);
//提供服务器的ip 和端口
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
//连接服务器
if (!socketChannel.connect(inetSocketAddress)) {
while (!socketChannel.finishConnect()){
System.out.println("因为连接需要事件,客户端不会阻塞,可以做其他工作...");
}
}
//.... 如果连接成功,就发送数据
String str = "Hello,清龙~";
//Wraps a byte array into buffer
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
//发送数据,将buffer 数据写入channel
socketChannel.write(buffer);
System.in.read();
}
}
服务端:
package com.netty.NioDemo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
/**
* @version V1.0.0
* @author: WangQingLong
* @date: 2020/12/7 23:22
* @description:
*/
public class NIOServer {
public static void main(String[] args) throws Exception {
//创建ServerSocketChannel -> ServerSocket
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//得到一个Selector对象
Selector selector = Selector.open();
//绑定一个端口6666,在服务器端监听
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
//设置为非阻塞
serverSocketChannel.configureBlocking(false);
//把serverSocketChannel注册到selector 关心 事件为 op_accept
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//循环等待客户端连接
while (true){
//这里我们等待1秒,如果没有事件发生,返回
//没有事件发生则返回0
if(selector.select(1000)==0){
System.out.println("服务器等待了1秒,无连接" );
continue;
}
//如果返回的>0,就获取到相关的selectionkey集合
//1.如果返回的>0,表示已经获取到关注的事件
//2. selector.selecterKeys()返回关注事件的集合
//通过selectionkeys 返回获取通道
Set<SelectionKey> selectionKeys = selector.selectedKeys();
//遍历set<SelectionKey>,使用迭代器遍历
Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
while (keyIterator.hasNext()){
//获取到selectionKey
SelectionKey key = keyIterator.next();
//根据key 对应的通道发生的事件做相应处理
if (key.isAcceptable()){ //如果是op_accept,有新的客户端连接
//该客户端生成一个SocketChanel
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("有一个socketChannel客户端连接进来了:"+socketChannel.hashCode());
//将 SocketChannel 设置为非阻塞
socketChannel.configureBlocking(false);
//将socketChannel注册到selector,关注事件为OP_Read.同时给socketChannel关联一个Buffer
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
if (key.isReadable()){ //发生op_read
//通过key,反向获取到对应的Channel
SocketChannel channel = (SocketChannel) key.channel();
//获取到该Channel关联的Buffer
ByteBuffer buffer = (ByteBuffer) key.attachment();
channel.read(buffer);
System.out.println("From 客户端" + new String(buffer.array()));
}
//手动从集合中移除当前的selectionKey ,防止重复操作
keyIterator.remove();
}
}
}
7.2. SelectionKey
SelectionKey,表示 Selector 和网络通道的注册关系, 共四种:
- int OP_READ:代表读操作,值为 1
- int OP_WRITE:代表写操作,值为 4
- int OP_CONNECT:代表连接已经建立,值为 8
- int OP_ACCEPT:有新的网络连接可以 accept,值为 16
源码中:
public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;
相关方法:
public abstract class SelectionKey {
public abstract Selector selector();//得到与之关联的 Selector 对象
public abstract SelectableChannel channel();//得到与之关联的通道
public final Object attachment();//得到与之关联的共享数据
public abstract SelectionKey interestOps(int ops);//设置或改变监听事件
public final boolean isAcceptable();//是否可以 accept
public final boolean isReadable();//是否可以读
public final boolean isWritable();//是否可以写
}
7.3. ServerSocketChannel
ServerSocketChannel 在服务器端监听新的客户端 Socket 连接
相关方法如下:
public abstract class ServerSocketChannel extends AbstractSelectableChannel
implements NetworkChannel{
public static ServerSocketChannel open() //得到一个 ServerSocketChannel 通道
public final ServerSocketChannel bind(SocketAddress local)//设置服务器端端口号
//设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
public final SelectableChannel configureBlocking(boolean block)
public SocketChannel accept()//接受一个连接,返回代表这个连接的通道对象
public final SelectionKey register(Selector sel, int ops)//注册一个选择器并设置监听事件
}
7.4 . SocketChannel
SocketChannel,网络 IO 通道,具体负责进行读写操作。NIO 把缓冲区的数据写入通道,或者把通道里的数 据读到缓冲区
相关方法如下:
public abstract class SocketChannel extends AbstractSelectableChannel
implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel{
public static SocketChannel open();//得到一个 SocketChannel 通道
//设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
public final SelectableChannel configureBlocking(boolean block);
public boolean connect(SocketAddress remote);//连接服务器
public boolean finishConnect();//如果上面的方法连接失败,接下来就要通过该方法完成连接操作
public int write(ByteBuffer src);//往通道里写数据
public int read(ByteBuffer dst);//从通道里读数据
//注册一个选择器并设置监听事件,最后一个参数可以设置共享数据
public final SelectionKey register(Selector sel, int ops, Object att);
public final void close();//关闭通道
}
8. 应用实例-群聊系统
客户端:
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;
import java.util.Set;
public class GroupChatClient {
//定义相关的属性
private final String HOST = "127.0.0.1"; // 服务器的ip
private final int PORT = 6667; //服务器端口
private Selector selector;
private SocketChannel socketChannel;
private String username;
//构造器, 完成初始化工作
public GroupChatClient() throws IOException {
selector = Selector.open();
//连接服务器
socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1", 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();
while (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());
}
}
iterator.remove(); //删除当前的selectionKey, 防止重复操作
} else {
//System.out.println("没有可以用的通道...");
}
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
//启动我们客户端
GroupChatClient chatClient = new GroupChatClient();
//启动一个线程, 每个3秒,读取从服务器发送数据
new Thread() {
public void run() {
while (true) {
chatClient.readInfo();
try {
Thread.currentThread().sleep(3000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
//发送数据给服务器端
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
chatClient.sendInfo(s);
}
}
}
服务端:
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;
private static final int PORT = 6667;
//构造器
//初始化工作
public GroupChatServer() {
try {
//得到选择器
selector = Selector.open();
//ServerSocketChannel
listenChannel = ServerSocketChannel.open();
//绑定端口
listenChannel.socket().bind(new InetSocketAddress(PORT));
//设置非阻塞模式
listenChannel.configureBlocking(false);
//将该listenChannel 注册到selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
}catch (IOException e) {
e.printStackTrace();
}
}
//监听
public void listen() {
System.out.println("监听线程: " + Thread.currentThread().getName());
try {
//循环处理
while (true) {
int count = selector.select();
if(count > 0) {//有事件处理
//遍历得到selectionKey 集合
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
//取出selectionkey
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() + " 上线 ");
}
if(key.isReadable()) { //通道发送read事件,即通道是可读的状态
//处理读 (专门写方法..)
readData(key);
}
//当前的key 删除,防止重复处理
iterator.remove();
}
} else {
System.out.println("等待....");
}
}
}catch (Exception e) {
e.printStackTrace();
}finally {
//发生异常处理....
}
}
//读取客户端消息
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);
//根据count的值做处理
if(count > 0) {
//把缓存区的数据转成字符串
String msg = new String(buffer.array());
//输出该消息
System.out.println("form 客户端: " + msg);
//向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
sendInfoToOtherClients(msg, channel);
}
}catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress() + " 离线了..");
//取消注册
key.cancel();
//关闭通道
channel.close();
}catch (IOException e2) {
e2.printStackTrace();;
}
}
}
//转发消息给其它客户(通道)
private void sendInfoToOtherClients(String msg, SocketChannel self ) throws IOException{
System.out.println("服务器转发消息中...");
System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
//遍历 所有注册到selector 上的 SocketChannel,并排除 self
for(SelectionKey key: selector.keys()) {
//通过 key 取出对应的 SocketChannel
Channel targetChannel = key.channel();
//排除自己
if(targetChannel instanceof SocketChannel && targetChannel != self) {
//转型
SocketChannel dest = (SocketChannel)targetChannel;
//将msg 存储到buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//将buffer 的数据写入 通道
dest.write(buffer);
}
}
}
public static void main(String[] args) {
//创建服务器对象
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}