概述
nio故名思意为非阻塞型io但是在java中nio其实并非如此 在java中nio设计的模式为异步阻塞模型也叫reactor模型
介绍
nio主要由三个部分组成 selector, channel ,buffer . select 通过select方法阻塞监听channe的读写l事件 channel通过buffer将读取的信息写入buffer中去或者通过buffer中的信息将该信息写入目标区域中。
大致运行流程
selector通过阻塞的方法select()监听事件 当有事件请求进行io操作的时候则由channel进行相应的读写事件
channel读取或者要写入的事件通过buffer进行硬盘的写入或者读取数据的存放。
示例
package com.xiao.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
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.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class NioServer {
private static Map<String,SocketChannel> clientMap =new HashMap<>();
public static void main(String args[]) throws IOException{
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
ServerSocket serverSocket=serverSocketChannel.socket();
InetSocketAddress socketAddress=new InetSocketAddress(8899);
serverSocket.bind(socketAddress);
Selector selector=Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true){
try {
selector.select();
Set<SelectionKey> selectionKeys=selector.selectedKeys();
selectionKeys.forEach(selectionKey -> {
try {
final SocketChannel client;
if (selectionKey.isAcceptable()){
ServerSocketChannel serverSocketChannel1=(ServerSocketChannel) selectionKey.channel();
client=serverSocketChannel.accept();
client.configureBlocking(false);
client.register(selector,SelectionKey.OP_READ);
String key="["+ UUID.randomUUID()+"]";
clientMap.put(key,client);
}else if (selectionKey.isReadable()){
client=(SocketChannel) selectionKey.channel();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
int count=client.read(byteBuffer);
if (count>0){
byteBuffer.flip();
Charset charset=Charset.forName("UTF-8");
String receivemsg=String.valueOf(charset.decode(byteBuffer).array());
System.out.println("msg: "+receivemsg);
String sendkey=null;
for (Map.Entry<String,SocketChannel>entry :clientMap.entrySet() ){
if (client==entry.getValue()){
sendkey=entry.getKey();
break;
}
}
for (Map.Entry<String,SocketChannel>entry :clientMap.entrySet()){
SocketChannel socketChannel=entry.getValue();
ByteBuffer byteBuffer1=ByteBuffer.allocate(1024);
byteBuffer1.put(( sendkey+":"+receivemsg).getBytes());
byteBuffer.flip();
socketChannel.write(byteBuffer);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
});
selectionKeys.clear();
}catch (Exception e){
e.printStackTrace();
}
}
}
}