- 1.1、NIO基本介绍?
- 1.2、NIO、BIO的比较
- 1.3、NIO三大核心
- Buffer缓冲区
- 缓冲区的基本属性
- Channel通道
- 通道Channel概述
- 常见的Channel实现类
- 案例:复制文件
- Selector选择器
- 选择器概述
- 1.4、NIO非阻塞式网络通信原理分析
- 服务端流程
- 客户端流程
- 1.5、NIO非阻塞式案例
- 服务器端
- 客户端
- 1.6、NIO下群聊系统
- 客户端
- 服务器端
1.1、NIO基本介绍?
- NIO与原来的IO有同样的作用和目的,但是使用方式不同,NIO支持面向缓冲区的、基于通道的IO操作。NIO将以更高效的方式进行文件的读写操作。NIO可以理解为非阻塞IO,传统的IO的read和write只能阻塞执行,线程在读写IO期间不能干其他的事情,比如调用socket。read()时,如果服务器一直没有传数据过来,线程就一直阻塞,而NIO中可以配置socket为非阻塞模式
- NIO三大核心部分:Channel(通道)、Buffer(缓冲区)、Selector(选择器)
- JAVA NIO 的非阻塞模式,使一个线程从某通道发送请求或读取数据,但是他进能得到目前可用的数据,如果目前没有可用数据时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变得可以读取之前,该线程可以继续做其他的事情。非阻塞写也是这样,一些线程请求写入一些数据到某通道,但不需要等待他完全写入,这个线程同时可以去做别的事情。
- BIO以流的方式处理数据,而NIO以块的方式处理数据,块I/O的效率比流I/O高很多
- BIO是阻塞的NIO是非阻塞的
- BIO时基于字节流和进行操作,而NIO基于Channel(通道)和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Select(选择器)用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道
| BIO | NIO |
|---|---|
| 面向缓冲区(Buffer) | 面向流(stream) |
| 非阻塞(Non Blocking IO) | 阻塞(Biocking IO) |
| 选择器(Selectors) |
缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。
缓冲区的基本属性- 容量(capacity):作为一个内存块,Buffer具有一定的固定大小,也称为“容量”,缓冲区容量不能为负,并且创建后不能更改
- 限制(limit):表示缓冲区可以操作数据的大小(limit后数据不能进行读写)。缓冲区的限制不能为负,并且不能大于其容量写入模式,限制等于buffer的容量。读取模式下,limit等于写入的数据量。
- 位置(position):下一个要读取或写入数据的索引。缓冲区的位置不能为负,且不能大于其限制。
- 标记(mark)与重置(reset):标记是一个索引,通过Buffer的mark()方法指定Buffer中的一个特定的position,之后可以通过调用reset()方法恢复到这个position。
- 标记、位置、限制、容量遵循下列关系:0<=mark<=position<=limit<=capacity
buffer的常用方法
Channel通道
JVA NIO 的通道类似流,但又有些不同:既可以从通道中读取数据,又可以写数据的通道。但流的(input或output)读写通常是单向的。通道可以非阻塞读取和写入通道,通道可以支持读取或写入缓冲区也支持异步的读写。
通道Channel概述Channel表示IO源与目标打开的连接。Channel类似于传统的“流”。只不过Channel本身不能直接访问数据,Channel只能与Buffer进行交互。
1.NIO的通道类似于流,但有些区别:
- 通道可以同时进行读写
- 通道可以实现异步读写数据
- 通道可以从缓冲读数据,也可以写数据到缓冲
2.BIO中的stream是单向的,例如FileInputStream对象只能进行读取数据的操作,而NIO中的通道(Channel)是双向的,可以读操作,可以写操作。
3.Channel在NIO中是一个接口
- FileChannel:用于读取、写入、映射和操作文件的通道
- DatagramChannel:通过UDP读取网络中的数据通道
- SocketChannel:通过TCP读写网络中的数据
- ServerSocketChannel:可以监听新进来的TCP连接,对每一个新进来的都会创建一个SocketChannel。
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelTest {
public static void main(String[] args) throws IOException {
File file = new File("D:\视频\m.mp4");
File destFile = new File("D:\视频\new1.mp4");
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(destFile);
//得到文件通道
FileChannel isChannel = fis.getChannel();
FileChannel osChannel = fos.getChannel();
//分配缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true){
//必须先清空缓冲区再写入数据到缓冲区
buffer.clear();
//开始读取一次数据
int flag = isChannel.read(buffer);
if (flag == -1){
break;
}
//已经读取了数据将其转换为可读模式
buffer.flip();
osChannel.write(buffer);
}
isChannel.close();
osChannel.close();
System.out.println("复制完成!");
}
}
Selector选择器
Selector是一个JAVA NIO组件,可以检查一个或多个NIO通道,并确定哪些通道已经准备好进行读取或写入。这样,一个单独的线程就可以管理多个channel,从而管理多个网络连接,提高效率。
选择器概述选择器(Selector)是SelectableChannel对象的多路复用器,Selector可以同时监控多个SelectableChannel的IO状况,也就是说,利用Selector可使一个单独的线程管理多个Channe。Selector是非阻塞IO的核心。
- Java的NIO,用非阻塞的IO方式。可以用一个线程,处理多个客户端连接,就会使用到Selectro(选择器)
- Selector能够检测多个注册的通道上是都有事件发生(注意:多个Channel以事件的方式可以注册到同一个Selector),如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求。
- 只有在连接/通道真正有读写事件发生时,才会进行读写,就大大减少了系统的开销,并且不必为每个连接都创建一个线程,不用去维护多个线程
- 避免了多线程之间的上下文切换导致的开销
- 创建一个selector的实例
1.通过调用selector的open方法实例出对象
Selector selector = Selector.open();
2.注册channel上事件
注册关注事件,channel提供的register方法,第一个参数传递的是selector实例,第二个参数传递的是感兴趣事件
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
3.使用selector监听器来监听事件是否完成
等待内核返回就绪事件
selector.select();
阻塞等待内核返回结果,告诉用户那些关注的事件完成
4.遍历感兴趣事件集合
SetselectionKeys = selector.selectedKeys();
返回的是Set类型集合,通过迭代器进行遍历
感兴趣集合就是已注册并且已准备就绪的事件
如果还有关注事件,则跳转到第三步继续监听
5.最终关闭复用器
- 每个channel都会对应一个Buffer
- 一个线程对应一个Selector,一个人Selector对应多个channel(l连接)
- 程序切换到哪个channel是由事件决定的
- Selector会根据不同的事件,在各个管道上切换
- Buffer就是一个内存块,底层是一个数组
- 数据的读取写入是通过Buffer完成的,BIO中要么是输入流,或者输出流,不能双向,但是NIO的Buffer是可以读也可以写
- 当客户端连接服务端时,服务端会通过ServerSocketChannel得到SocketChannel
ServerSocketChannel ssChannel = ServerSocketChannel.open()
- 切换非阻塞模式
ss.Channel.configureBlocking(false);
- 绑定连接
ssChannel.bind(new InetSocketAddress(6666));
- 获取选择器
Selector selector = Selector.opean();
- 将通道注册到选择器上,并且指定“监听接收事件”
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
- 轮询式的获取选择器上已经“准备就绪”的事件
//轮询式的获取选择器上已经“准备就绪”的事件
while(selector.select()>0){
System.out.println("轮一轮");
//获取当前选择器中所有注册的“选择键(已就绪的监听事件)”
Iterator it = selector.selectedKeys().iterator();
while(it.hashNext()){
//获取准备“就绪”的事件
SelectionKey sk = it.next();
//判断具体是什么事件准备就绪
if(sk.isAcceptable){
//若“接收就绪”,获取客户端连接
SocketChannel sChannel = ssChannel.accept();
//切换非阻塞模式
sChannel.configureBlocking(false);
//将该通道注册到选择器上
sChannel.register(selector,selectionKey.OP_READ);
}else if(sk.isReadable){
//获取当前选择器上“读就绪”状态通道
SocketChannel sChannel = (socketChannel) sk.channel();
//读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = 0;
while ((len = sChannel.read(buf))>0){
buf.flip();
Syetem.out.println(new String(buf.array(),0,len));
buf.clear();
}
}
//取消选择键
it.remove();
}
}
客户端流程
- 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",6666))
- 切换非阻塞模式
sChannel.configureBlocking(false);
- 分派指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
- 发送数据给服务器
Scanner sc = new Scanner(System.in);
while(sc.hashNext()){
String str = sc.nextLine();
buf.put(new SimpleDateFormat("yyyy/MM/ddHH:mm:ss").format(System.currentTimeMillis())+"n"+str).getBytes());
buf.flip;
sChannel.write(buf);
buf.clear;
}
1.5、NIO非阻塞式案例
服务器端
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
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.sql.SQLOutput;
import java.util.Iterator;
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("-------服务端启动-------");
//1.获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
//2.切换为非阻塞模式
ssChannel.configureBlocking(false);
//3.绑定连接的端口
ssChannel.bind(new InetSocketAddress(6666));
//4.获取选择器
Selector selector = Selector.open();
//5.将通道注册到选择器上,并且开始指令监听接收事件
ssChannel.register(selector,SelectionKey.OP_ACCEPT);
//6.使用Selector选择器轮询已经就绪好的事件
while (selector.select()>0){
System.out.println("开始一轮事件处理");
//7.获取选择器中的所有注册的通道中已经就绪好的事件
Iterator it = selector.selectedKeys().iterator();
//8.开始遍历准备好的事件
while (it.hasNext()){
//提取当前事件
SelectionKey sk = it.next();
//9.判断这个事件是什么
if (sk.isAcceptable()){
//10。直接获取当前接入的客户端通道
SocketChannel sChannel = ssChannel.accept();
//11.接换成非阻塞模式
sChannel.configureBlocking(false);
//12.注册到选择器
sChannel.register(selector,SelectionKey.OP_READ);
}else if (sk.isReadable()){
//13.获取当前选择器上读就绪事件
SocketChannel sChannel = (SocketChannel) sk.channel();
//14.读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = 0;
while ((len = sChannel.read(buf))>0){
buf.flip();
System.out.println(new String(buf.array(),0,len));
buf.clear();//清除之前的数据
}
}
it.remove();//处理完毕之后移除当前事件
}
}
}
}
客户端
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
//1.获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.01", 6666));
//2.切换成非阻塞模式
sChannel.configureBlocking(false);
//3.分配缓冲区大小
ByteBuffer buf = ByteBuffer.allocate(1024);
//4.发送数据给服务端
Scanner scanner = new Scanner(System.in);
while (true){
System.out.print("请输入:");
String msg = scanner.nextLine();
buf.put(("黑黑:"+msg).getBytes());
buf.flip();
sChannel.write(buf);
buf.clear();
}
}
}
1.6、NIO下群聊系统
- 编写一个NIO群聊系统,实现客户端与客户端的通信需求(非阻塞)
- 服务器端:可以监测用户上线,离线,并实现消息转发功能
- 客户端:通过channel可以无阻塞发送消息给其他所有客户端用户,同时可以接受其他客户端通过服务端转发来的消息
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;
public class Client {
//1.定义相关属性
private Selector selector;
private static int PORT = 6666;
private SocketChannel sChannel;
//2.初始化
public Client(){
try {
//a.创建选择器
selector = Selector.open();
//b、连接服务端
sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",PORT));
//c.设置非阻塞
sChannel.configureBlocking(false);
sChannel.register(selector,SelectionKey.OP_READ);
System.out.println("当前客户端准备完成");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
//定义一个线程监听服务端发送来的读消息事件
new Thread(new Runnable() {
@Override
public void run() {
try {
client.readInfo();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String s = scanner.nextLine();
client.sendToServer(s);
}
}
private void sendToServer(String s) {
try {
sChannel.write(ByteBuffer.wrap(("白白说:"+s).getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
private void readInfo() throws IOException {
while (true) {
if (selector.select() > 0) {
Iterator iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buf = ByteBuffer.allocate(1024);
sc.read(buf);
System.out.println(new String(buf.array()).trim());
}
iterator.remove();
}
}
}
}
}
服务器端
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class Server {
//1.定义成员属性:选择器、服务端通道、端口
private Selector selector;
private ServerSocketChannel ssChannel;
private static final int PORT = 6666;
//2、定义初始化代码逻辑
public Server(){
try {
//接受选择器
selector = Selector.open();
//获取通道
ssChannel = ServerSocketChannel.open();
//绑定客户端端口
ssChannel.bind(new InetSocketAddress(PORT));
//设置非阻塞模式
ssChannel.configureBlocking(false);
//把通道注册到选择器上
ssChannel.register(selector,SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//创建服务端对象
Server server = new Server();
//开始监听客户端的各种消息事件:连接、群聊消息、离线消息
server.listen();
}
private void listen() {
try {
while (selector.select()>0){
//a.获取选择器中所有所有注册通道的就绪事件
Iterator it = selector.selectedKeys().iterator();
//b.开始遍历这些事件
while (it.hasNext()){
//提取这个事件
SelectionKey sk = it.next();
//c.判断事件类型
if (sk.isAcceptable()){
//客户端接入请求
SocketChannel sChannnel = ssChannel.accept();
sChannnel.configureBlocking(false);
sChannnel.register(selector,SelectionKey.OP_READ);
}else if (sk.isReadable()){
//处理这个客户端的消息,接收他然后实现转发逻辑
readClientData(sk);
}
it.remove();//处理完毕,移除当前事件
}
}
}catch (Exception e){
e.printStackTrace();
}
}
//接收当前客户端的信息,转发给其他全部客户端通道
private void readClientData(SelectionKey sk) {
SocketChannel sChannel = null;
try{
//得到当前客户端通道
sChannel = (SocketChannel) sk.channel();
ByteBuffer buf = ByteBuffer.allocate(1024);
int count = sChannel.read(buf);
if (count>0){
buf.flip();
//提取读取到的信息
String msg = new String(buf.array(),0,buf.remaining());
System.out.println("接收到客户端消息:"+msg);
//把消息推送给所有人
sendMsgToAllClient(msg,sChannel);
}
}catch (Exception e){
try {
System.out.println("有人离线"+sChannel.getRemoteAddress());
//当前客户端离线
sk.cancel();
sChannel.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//把当前客户端消息推送给当前全部在线注册的channel
private void sendMsgToAllClient(String msg, SocketChannel sChannel) throws IOException {
//System.out.println("服务端开始转发这个消息:"+Thread.currentThread().getName());
for (SelectionKey key:selector.keys()){
SocketChannel channel = (SocketChannel) key.channel();
//不要把消息给自己
if (!(sChannel == channel)){
ByteBuffer buf = ByteBuffer.wrap(msg.getBytes());
channel.write(buf);
}
}
}
}



