一张图描述 NIO 的 Selector 、 Channel 和 Buffer 的关系:
Buffer(缓冲区): 缓冲区本质上是一个可以读写数据的内存块,可以理解成一个容器,该容器提供了一组方法,可以更轻松的使用内存块。缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变换。
Channel提供从文件、网络读取数据的渠道,但是读取或者写入的数据都必须经过Buffer
NIO的通道类似于流,但又有些区别
通道可以从缓冲读数据,也可以写数据到缓冲
Channel 是 NIO中的一个接口 public interface Channel extends Closeable 、
常用的channel类有:FileChannel,DatagramChannel,ServerSocketChannel,SocketChannel。【FileChannel用于文件数据的读写,DatagramChannel用于UDP数据的读写,ServerScoketChannel SocketChannel用于TCP数据的读写】
FileChannel 主要是用来对本地文件进行IO操作,常见的方法有:
【实例要求】
1、使用前面学习的ByteBuffer,FileChannel 将“hello,尚硅谷” 写入到file01.txt中
2、文件不存在则创建文件
public class NIOFileChannel01 {
public static void main(String[] args) throws IOException {
String str= "hello,尚硅谷";
FileOutputStream fileOutputStream = new FileOutputStream("E://file01.txt");
// channel的真是类型是 FileChannelImpl
FileChannel channel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// 将str扔到byteBuffer中
byteBuffer.put(str.getBytes());
// 对 byteBuffer 进行反转
byteBuffer.flip();
// 对于channel 来说是将 buffer中的数据写入到channel中
channel.write(byteBuffer);
// 关闭流
fileOutputStream.close();
}
}
public class NIOFileChannel02 {
public static void main(String[] args) throws IOException {
File file = new File("E://file01.txt");
FileInputStream fileInputStream = new FileInputStream(file);
// channel的真是类型是 FileChannelImpl
FileChannel channel = fileInputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
channel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
// 关闭流
fileInputStream.close();
}
}
public class NIOFileChannel03 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("1.txt");
FileChannel fileChannel01 = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
FileChannel fileChannel02 = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
while (true) { //循环读取
//这里有一个重要的操作,一定不要忘了
/*
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
*/
byteBuffer.clear(); //清空buffer
int read = fileChannel01.read(byteBuffer);
System.out.println("read =" + read);
if(read == -1) { //表示读完
break;
}
//将buffer 中的数据写入到 fileChannel02 -- 2.txt
byteBuffer.flip();
fileChannel02.write(byteBuffer);
}
//关闭相关的流
fileInputStream.close();
fileOutputStream.close();
}
}
public class NIOFileChannel04 {
public static void main(String[] args) throws Exception {
//创建相关流
FileInputStream fileInputStream = new FileInputStream("d:\\a.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("d:\\a2.jpg");
//获取各个流对应的filechannel
FileChannel sourceCh = fileInputStream.getChannel();
FileChannel destCh = fileOutputStream.getChannel();
//使用transferForm完成拷贝
destCh.transferFrom(sourceCh,0,sourceCh.size());
//关闭相关通道和流
sourceCh.close();
destCh.close();
fileInputStream.close();
fileOutputStream.close();
}
}
1)ByteBuffer支持类型化的put和get,put放入的是什么数据类型,get就需要使用相应的数据类型来取出,否则就可能有 BufferUnderflowException 异常
2)可以将一个普通Buffer转换成只读Buffer
//得到一个只读的Buffer
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
3)NIO还提供了MapperedByteBuffer,可以让文件直接在内存中(堆外的内存)进行修改,而如何同步到文件由NIO来完成
4)前面我们讲的读写操作,都是通过一个Buffer完成的,NIO还支持通过多个Buffer(即Buffer数组)来完成读写操作,即Scattering 和 Gathering 【分散和聚合】
1)Java的NIO,用的非阻塞的IO方式。可以用一个线程来处理多个客户端的连接,此时就会用到Selector选择器
2)多个Channel以事件的方式注册到同一个Selector,Selector可以检测到多个注册的channel上是否有事件发生,
如如果有事件发生,便去获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道。
3)只有在连接真正有读写事件发生时,才会进行读写,大大减少了系统的开销。并且不会为每一个连接都创建一个线程,不用去维护多个线程
4)避免了多线程之间的上下文切换导致的开销
【总结】多个Channel以事件的方式注册到同一个Selector,Selector可以检测到多个注册的channel上是否有事件发生
Selector,SelectionKey,ServerSocketChannel,SocketChannel之间的关系
【案例要求】
编写一个NIO入门程序,实现服务器和客户端之间的数据简单通讯(非阻塞)
代码
public class NIOServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 绑定一个端口,在服务器端进行监听
serverSocketChannel.socket().bind(new InetSocketAddress(6666));
// 设置为非阻塞
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
// serverSocketChannel 注册到selector, 关心事件为 OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 循环等待客户端进行连接
while (true) {
if (selector.select(1000) == 0) {
// System.out.println("服务器端等待了一秒,无连接");
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// selector监听到 OP_ACCEPT事件,表示有新的客户端连接
if (key.isAcceptable()) {
System.out.println("监听到客户端的注册事件,将客户端注册到server =======> ");
// 给该客户端生成一个socketChannel
SocketChannel socketChannel = serverSocketChannel.accept();
// 将socketChannel设置成非阻塞
socketChannel.configureBlocking(false);
// 将SocketChannel注册到selector,关注事件设置为 op_read
socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
} else if (key.isReadable()) {
// 通过key反向获取到channel
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
channel.read(byteBuffer);
System.out.println("收到客户端传递过来的消息:" + new String(byteBuffer.array()));
}
iterator.remove();
}
}
}
}
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("因为连接需要时间,客户端不会阻塞,可以做其它工作..");
}
}
while (true) {
//...如果连接成功,就发送数据
Scanner scanner = new Scanner(System.in);
String in = scanner.nextLine();
//Wraps a byte array into a buffer
ByteBuffer buffer = ByteBuffer.wrap(in.getBytes());
//发送数据,将 buffer 数据写入 channel
socketChannel.write(buffer);
}
}
}
1、SelectionKey 表示 Selector和网络通道之间的注册关系
selector.selectedKeys(): 表示当前有哪些注册到selector的通道发生了事件
selector.keys() : 表示当前有注册到selector的所有通道
网络IO通道,具体负责进行读写操作。NIO将buffer中的内容写入channel,或者将channel中的内容读到buffer
package com.atgui.nio.qunliao;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
public class GroupChatServer {
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6667;
public GroupChatServer() {
try {
selector = Selector.open();
listenChannel = ServerSocketChannel.open();
listenChannel.socket().bind(new InetSocketAddress(PORT));
listenChannel.configureBlocking(false);
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
public void listen() {
try {
// chat服务器线程一直循环进行监听
while (true) {
int count = selector.select(2000);
if (count > 0) {
// 取出当前有事件的集合
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
// 监听到有客户端进行连接
if (key.isAcceptable()) {
SocketChannel socketChannel = listenChannel.accept();
socketChannel.configureBlocking(false);
// 将 socketChannel 也注册到 selector上
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(socketChannel.getRemoteAddress() + "上线");
}
// 发生了事件的通道是可读的状态
if (key.isReadable()) {
readData(key);
}
// 把当前的SelectionKey删除
iterator.remove();
}
} else {
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
//
private void readData(SelectionKey key) {
SocketChannel channel = null;
try {
// 由 SelectionKey 反向得到 channel
channel = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// 返回读取到的长度
int count = channel.read(byteBuffer);
if (count > 0) {
String message = new String(byteBuffer.array());
System.out.println("from 客户端: " + message);
// 向其他客户端转发消息
broadMessage(message, channel);
}
} catch (IOException e) {
try {
System.out.println(channel.getRemoteAddress() + "离线");
// 用户离线了,取消注册、关闭通道
key.cancel();
channel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// 转发消息给所有通道,【注意】去掉自己
private void broadMessage(String message, SocketChannel self) throws IOException {
System.out.println("服务器开始转发消息");
// 获取所有注册到selector的 SocketChannel,并排除自己
for (SelectionKey key : selector.keys()) {
SelectableChannel targetChannel = key.channel();
if (targetChannel instanceof SocketChannel && targetChannel != self) {
ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
((SocketChannel) targetChannel).write(byteBuffer);
}
}
}
public static void main(String[] args) {
//创建服务器对象
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}
package com.atgui.nio.qunliao;
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(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
//发送数据给服务器端
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
chatClient.sendInfo(s);
}
}
}
【没看】之后进行补充