Java Nio选择器Selector

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15144655/article/details/80928207

Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接 ,减少服务器的性能开销。

创建Selector

  • 通过Selector 提供的静态方法创建    Selector selector = Selector.open();

  • 通过SelectorProvider获取选择器

SelectorProvider selectorProvider = SelectorProvider.provider();
Selector selector = selectorProvider.openSelector();

将通道注册到选择器上

通过ServerSocketChannel.register(Selector sel, int ops)方法注册的selecor中

//获取通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//切换到非堵塞模式
serverSocketChannel.configureBlocking(false);
//绑定端口号
serverSocketChannel.bind(new InetSocketAddress(8080));
//获取选择器
Selector selector = Selector.open();
//将通道注册到选择器上,并且指定“监听接收事件”
SelectionKey key = serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);

与selector使用,channel必须处于非堵塞状态下,FileChannel无法切换到非堵塞状态下将不能与selector一起使用。

register()中的第二个参数表示通道监听的事件一共四种状态

  • SelectionKey.OP_CONNECT 连接
  • SelectionKey.OP_ACCEPT 接收
  • SelectionKey.OP_READ 读
  • SelectionKey.OP_WRITE 写

单一个通道监听多种事件时使用位或多种事件如: SelectionKey.OP_CONNECT|SelectionKey.OP_ACCEPT

Selector的select()方法

Selector中注册了一或多个通道,就可以调用几个重载的select()方法。这些方法返回通道的事件(如连接、接受、读或写)已经准备就绪的那些通道。换句话说,如果你对“读就绪”的通道感兴趣,select()方法会返回读事件已经就绪的那些通道。

下面是select()方法:

  • int select()
  • int select(long timeout)
  • int selectNow()

select()阻塞到至少有一个通道在你注册的事件上就绪了。

select(long timeout)和select()一样,除了最长会阻塞timeout毫秒(参数)。

selectNow()不会阻塞,不管什么通道就绪都立刻返回(此方法执行非阻塞的选择操作。如果自从前一次选择操作后,没有通道变成可选择的,则此方法直接返回零。)。

select()方法返回的int值表示有多少通道已经就绪。亦即,自上次调用select()方法后有多少通道变成就绪状态。如果调用select()方法,因为有一个通道变成就绪状态,返回了1,若再次调用select()方法,如果另一个通道就绪了,它会再次返回1。如果对第一个就绪的channel没有做任何操作,现在就有两个就绪的通道,但在每次select()方法调用之间,只有一个通道就绪了。

selectedKeys()

一旦调用了select()方法,并且返回值表明有一个或更多个通道就绪了,然后可以通过调用selector的selectedKeys()方法,访问“选择健(已就绪的监听事件)”中的就绪通道。如下所示:

Set selectedKeys = selector.selectedKeys()

使用Selector实现非堵塞Socket

服务端

//1.获取通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2.切换到非堵塞模式
serverSocketChannel.configureBlocking(false);
//3.绑定端口号
serverSocketChannel.bind(new InetSocketAddress(8080));
//4.获取选择器
Selector selector = Selector.open();
//5.将通道注册到选择器上,并且指定“监听接收事件”
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
//6轮询式的获取选择器上已经‘准备就绪’的事件
while (selector.select()>0){
    //7 。获取当前选择器中所有注册的"选择健(已就绪的监听事件)"
    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()){
        //8.获取“准备就绪”的事件
        SelectionKey selectionKey = iterator.next();
         //9.判断具体事件,就绪
        if (selectionKey.isAcceptable()){
            //10.接收就绪,获取客户端连接
            SocketChannel socketChannel = serverSocketChannel.accept();
            //11,切换到非堵塞模式
            socketChannel.configureBlocking(false);
            //12.将客户端通道注册到选择器上
            socketChannel.register(selector,SelectionKey.OP_READ);
        }else if (selectionKey.isReadable()){
            //获取当前选择器上“读就绪”状态的通道
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //读取客户端传过来的数据
            int len = 0;
            while ((len = socketChannel.read(buffer))>0){
              buffer.flip();
              System.out.println(new String(buffer.array(),0,len));
              buffer.clear();  
          }
        }
        //取消选择键selectionKey
        iterator.remove();
    }
}

客户端

//1.获取通道
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8080));
//2.设置为非堵塞模式
socketChannel.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(1024);
//3.发送数据给服务端
//控制台输入数据
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
    String msg = scanner.next();
    buf.put(msg.getBytes());
    buf.flip();
    socketChannel.write(buf);
    buf.clear();
}
//4.关闭连接
socketChannel.close();

博客地址

更多示例代码

本文参考

猜你喜欢

转载自blog.csdn.net/qq_15144655/article/details/80928207