NIO:同步非阻塞模型
NIO中提供了选择器(Selector 类似底层操作系统提供的IO复用器:select、poll、epoll),也叫做多路复用器,作用是检查一个或者多个NIO Channel(通道)的状态是否是可读、可写。。。可以实现单线程管理多个channel,也可以管理多个网络请求
**Channel:**通道,用于IO操作的连接,在Java.nio.channels包下定义的,对原有IO的一种补充,不能直接访问数据需要和缓冲区Buffer进行交互
通道主要实现类:
SocketChannel:通过TCP读写网络中的数据,一般客户端的实现
ServerSocketChannel:监听新进来的TCP连接,对每一个连接都需要创建一个SocketChannel。一般是服务端的实现
Buffer:缓冲区,IO流中的数据需要经过缓冲区交给Channel
NIO的编程
服务端:
public class NIOServer {
public static void main(String[] args) {
ServerSocketChannel serverSocketChannel = null;
try {
//创建ServerSocketChannel通道实例
serverSocketChannel = ServerSocketChannel.open();
//绑定端口
serverSocketChannel.bind(new InetSocketAddress(9998));
System.out.println("服务端启动了");
//将serverSocketChannel设置为非阻塞 configureBlocking设置阻塞非阻塞 false:非阻塞 true:阻塞
serverSocketChannel.configureBlocking(false);
//创建selector选择器
Selector selector = Selector.open();
//将通道serverSocketChannel注册到选择器selector,关注可接受事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//等待监听结果,调用选择器的select阻塞等待,直到有事件发生才返回
while (selector.select() > 0) {
Iterator <SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey selectionKey = iterator.next();
iterator.remove();
//是否是可接受事件
if (selectionKey.isAcceptable()) {
System.out.println("可接受事件");
//有新用户连接
ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel();
//接受客户端的连接,通过accept(不在阻塞)接受一个SocketChannel通道
SocketChannel socketChannel = serverSocketChannel1.accept();
//设置socketChannel为非阻塞
socketChannel.configureBlocking(false);
//将socketChannel注册到选择器selector选择器,关注可读事件
socketChannel.register(selector, SelectionKey.OP_READ);
}
//是否是可读事件
if (selectionKey.isReadable()) {
System.out.println("可读事件");
//获取SocketChannel通道
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
//创建Buffer
ByteBuffer buffer = ByteBuffer.allocate(100);
//进行读取操作
socketChannel.read(buffer);
//进行读写模式的切换
buffer.flip();
//将数据从Buffer中读取
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
//打印结果
System.out.println("客户端:"+socketChannel.getRemoteAddress()+new String(bytes,0,bytes.length));
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally