selector的作用:
1.Java NIO 用非阻塞的IO方式,可以用一个线程,处理多个客户端连接,就会用到selector
2.Selector能够检测多个注册的通道上是否有事件发生,如果有时间发生,便获取时间然后针对每个时间进行对应的处理,这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求
3.只有在连接真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都去创建一个线程,不用去维护多个线程
4.避免了多线程之间的上下文切换导致的开箱
selector的特点:
1.Netty的IO线程NioEventLoop 聚合了Selector,可以同时并发处理成百上千个客户端连接
2.当线程从某客户端Socket通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务
3.线程通常将非阻塞IO的空闲时间用于在其他通道上执行IO操作,所以单独的线程可以管理多个输入和输出通道
4.由于读写操作都是非阻塞的,这就可以充分提升IO线程的运行效率,避免由于频繁IO阻塞导致的编程挂起
5.一个IO线程可以并发处理N个客户端连接和读写操作,这从根本上解决了传统同步阻塞IO一连接一线程模型,架构的性能,弹性伸缩能力和可靠性都得到了极大地提升
类与相关方法:
Selector是一个抽象类,实现了Closeable接口
static Selector open() : 得到一个Selector对象
int select(int timeout): 监控所有注册通道,当其中有IO操作可以进行时,将对应的SelectionKey加入到内部集合中并返回,参数用来设置超时时间,在时间内会阻塞
selector.wakeup(): 唤醒selector
selector.selectNow() : 不阻塞,立马返回
public Set selectedKys(): 从内部集合中得到所有的SelectionKey
关系图分析:
1.当客户端连接时,会通过ServerSocketChannel得到对应的ScoketChannel
2.将scoketChannel注册到Selector,一个Selector可以注册多个SocketChannel
3.注册后会返回一个selectionKey,会和该Selector关联,回合该Selector关联(集合)
4.Selector进行监听,select方法,返回有事件发生的通道的个数,
5.可以再次进一步得到各个selectionKey(有事件发生的)
6.通过selectionKey,反向获取SocketChannel
7.可以通过得到的Channel,完成业务
上面提到了selectionKey,下面来说说selectionKey的相关方法以及属性
和通道的注册关系:
int OP_ACCEPT 有新的连接可以accept 值为16
int OP_CONNECT 代表连接已经建立 值为8
int OP_READ 代表读操作,值为1
int OP_WRITE 代表写操作,值为4
相关方法
Selector selectro() 得到与之关联的通道
Object attachment() 得到与之关联的共享数据(缓冲池buffer)
SelectionKey intersOps(int ops) 设置或改变监听事件
boolean isAcceptabke() 是否可以accept
boolean isReadable()是否可读
boolean isWritable() 是否可写
使用案例:
完成一个服务端和客户端的通讯:
服务端:
package com.jym.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
/**
* @program: JymNetty
* @description: 服务器端
* @author: jym
* @create: 2020/02/02
*/
public class JymNioServer {
public static void main(String[] args) throws IOException {
// 创建ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 得到selector对象
Selector selector = Selector.open();
// 绑定端口
serverSocketChannel.socket().bind(new InetSocketAddress(7000));
// 设置非阻塞
serverSocketChannel.configureBlocking(false);
// 把serverSocketChannel注册到selector,关心时间为OP_ACCEPT
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 循环等待客户端连接
while (true){
//等待一秒, 没有事件发生
if(selector.select(1000)==0){
System.out.println("服务器等待了1秒,无连接");
continue;
}
// 有事件发生,就获取相关的SelectionKey集合
// 返回大于0,表示已经获取到关注的事件
// selector.selectedKeys()返回关注事件的集合
// 通过selectionKeys 反向获取管道
Set<SelectionKey> selectionKeys = selector.selectedKeys();
// 遍历集合
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
// 获取到SelectionKey
SelectionKey selectionKey = iterator.next();
// 根据key对应的通道,发生的事件来做相应的处理
// 连接事件
if(selectionKey.isAcceptable()&&selectionKey.isValid()){
System.out.println("客户端连接成功");
// 给该客户端生成一个SocketChannel
SocketChannel socketChannel = serverSocketChannel.accept();
// 将socketChannel设置为非阻塞
socketChannel.configureBlocking(false);
// 注册到selector 关注时间为OP_READ,同时给该socketChannel关联一个Buffer
socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
}
// 读取分支,读时间
if(selectionKey.isReadable()&&selectionKey.isValid()){
// 通过key 反向获取socketChannel
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
// 获取到该channel的buffer
ByteBuffer buffer = (ByteBuffer)selectionKey.attachment();
int read = socketChannel.read(buffer);
System.out.println("客户端数据为;" + new String(buffer.array()));
}
// 手动删除key 反正重复
iterator.remove();
}
}
}
}
客户端:
package com.jym.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/**
* @program: JymNetty
* @description: 客户端
* @author: jym
* @create: 2020/02/02
*/
public class JymNioClient {
public static void main(String[] args) throws IOException {
// 得到网络通道
SocketChannel socketChannel = SocketChannel.open();
// 非阻塞
socketChannel.configureBlocking(false);
// 设置IP 端口
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 7000);
// 连接服务器
if(!socketChannel.connect(inetSocketAddress)){
while (!socketChannel.finishConnect()){
System.out.println("连接需要时间,客户端可以做其他工作,不会阻塞");
}
}
// 如果连接成功,发送数据
String str = "hello,jym";
// 产生字节数组,到buffer里去
ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
// 发送数据
socketChannel.write(byteBuffer);
System.in.read();
}
}