Java NIO 教程(四)Selector

 

一. Selector概述

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

. 用法

  1. 步骤
    1. 创建Selector
    2. 向Selector注册通道,获取返回的SelectionKey
    3. 通过Selector选择通道
    4. 通过selector.selectedKeys()获取SelectionKey的集合
    5. 遍历集合判断是哪个状态然后对流进行操作
  2. 首先了解SelectionKey
    1. 如何获得?
      1. 当向Selector注册Channel时,register()方法会返回一个SelectionKey对象
      2. 或者使用selector.selectedKeys()获得一个Set<SelectionKey>的集合,对集合进行遍历获取SelectionKey
    2. 包含什么?
      • interest集合
        1. 定义:interest集合是你所选择的感兴趣的事件集合
        2. 用“位与”操作interest 集合和给定的SelectionKey常量,可以确定某个确定的事件是否在interest 集合中。
          int interestSet = selectionKey.interestOps();
          
          boolean isInterestedInAccept  = (interestSet & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;
          boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;
          boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;
          boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE;
          
      • ready集合
        1. ready 集合是通道已经准备就绪的操作的集合
        2. 获取ready集合,可以判断通道是否准备就绪
          1. 第一种判断方式:与insert集合相同
            //第一种判断方式:通过调用readOps()获取ready集合,判断方式和insert集合相同
            
            int readySet = selectionKey.readyOps();
            
            
          2. 第二种判断方式:selectionKey直接调用相应的~able()
            //第二种判断方式:调用selectionKey的方法
            
            selectionKey.isAcceptable();
            
            selectionKey.isConnectable();
            
            selectionKey.isReadable();
            
            selectionKey.isWritable();
        3. Channel
          //通过selectionKey获取channel
          
          Channel  channel  = selectionKey.channel();
        4. Selector
          //通过selectionKey获取selector
          
          Selector selector = selectionKey.selector();
        5. 附加的对象(可选)
          1. 将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象
            //第一种附加对象方法
            
            selectionKey.attach(theObject);
            
            Object attachedObj = selectionKey.attachment();
          2. 还可以在用register()方法向Selector注册Channel的时候附加对象
            //第二种附加对象方法
            
            SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);
  3. 具体实现
  • 创建Selector
    Selector selector = Selector.open();
  • 向Selector注册通道,获取返回的SelectionKey
    channel.configureBlocking(false);
    
    SelectionKey key = channel.register(selector,Selectionkey.OP_READ);
  • 通过Selector选择通道
    • 定义:调用几个重载的select()方法。返回你所感兴趣的事件(如连接、接受、读或写)已经准备就绪的那些通道。
    • 分类:
      1. int select()   阻塞到至少有一个通道在你注册的事件上就绪了。
      2. int select(long timeout)  timeout是最长阻塞的毫秒数
      3. int selectNow()  不管什么通道就绪都立刻返回(非阻塞的选择操作,如果自从前一次选择操作后,没有通道变成可选择的,则此方法直接返回零)
    • 注意:select()方法返回的int值表示有多少通道已经就绪。亦即,自上次调用select()方法后有多少通道变成就绪状态。如果调用select()方法,因为有一个通道变成就绪状态,返回了1,若再次调用select()方法,如果另一个通道就绪了,它会再次返回1。如果对第一个就绪的channel没有做任何操作,现在就有两个就绪的通道,但在每次select()方法调用之间,只有一个通道就绪了。
      int select()
      
      int select(long timeout)
      
      int selectNow()
  • 通过selector.selectedKeys()获取SelectionKey的集合
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    
    Iterator keyIterator = selectedKeys.iterator();
    
    while (keyIterator.hasNext()) {
    
        SelectionKey key = keyIterator.next();
    
        if (key.isAcceptable()) {
    
            // a connection was accepted by a ServerSocketChannel.
    
        } else if (key.isConnectable()) {
    
            // a connection was established with a remote server.
    
        } else if (key.isReadable()) {
    
            // a channel is ready for reading
    
        } else if (key.isWritable()) {
    
            // a channel is ready for writing
    
        }
    
        //Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除
    
        keyIterator.remove();
    
    }

 

实例:先运行WebServer再运行WebClit

WebServer:

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.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.util.Iterator;

import java.util.Set;



public class WebServer {

    public static void main(String[] args) {

        try {

            ServerSocketChannel ssc = ServerSocketChannel.open();

            ssc.socket().bind(new InetSocketAddress("127.0.0.1", 8000));

            ssc.configureBlocking(false);



            Selector selector = Selector.open();

            // 注册 channel,并且指定感兴趣的事件是 Accept

            ssc.register(selector, SelectionKey.OP_ACCEPT);



            ByteBuffer readBuff = ByteBuffer.allocate(1024);

            ByteBuffer writeBuff = ByteBuffer.allocate(128);

            writeBuff.put("received".getBytes());

            writeBuff.flip();



            while (true) {

                int nReady = selector.select();

                Set<SelectionKey> keys = selector.selectedKeys();

                Iterator<SelectionKey> it = keys.iterator();



                while (it.hasNext()) {

                    SelectionKey key = it.next();

                    it.remove();



                    if (key.isAcceptable()) {

                        // 创建新的连接,并且把连接注册到selector上,而且,

                        // 声明这个channel只对读操作感兴趣。

                        SocketChannel socketChannel = ssc.accept();

                        socketChannel.configureBlocking(false);

                        socketChannel.register(selector, SelectionKey.OP_READ);

                    }

                    else if (key.isReadable()) {

                        SocketChannel socketChannel = (SocketChannel) key.channel();

                        readBuff.clear();

                        socketChannel.read(readBuff);



                        readBuff.flip();

                        System.out.println("received : " + new String(readBuff.array()));

                        key.interestOps(SelectionKey.OP_WRITE);

                    }

                    else if (key.isWritable()) {

                        writeBuff.rewind();

                        SocketChannel socketChannel = (SocketChannel) key.channel();

                        socketChannel.write(writeBuff);

                        key.interestOps(SelectionKey.OP_READ);

                    }

                }

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}



 

WebClient:

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SocketChannel;



public class WebClient {

    public static void main(String[] args) throws IOException {

        try {

            //1.打开SocketChannel

            SocketChannel socketChannel = SocketChannel.open();

            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));



            //2.新建读,写buffer

            ByteBuffer writeBuffer = ByteBuffer.allocate(32);

            ByteBuffer readBuffer = ByteBuffer.allocate(32);



            //3.1.向writeBuffer中放入值

            writeBuffer.put("hello".getBytes());

            //3.2.将buffer从写转换成读

            writeBuffer.flip();



            while (true) {

                //3.3.使buffer的position置0

                writeBuffer.rewind();

                //3.4.将writeBuffer中的内容写入socketChannel

                socketChannel.write(writeBuffer);



                readBuffer.clear();

                //4.读取socketChannel的内容到readBuffer

                socketChannel.read(readBuffer);

                System.out.println(new String(readBuffer.array()));

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

 

  • 其他方法:
    1. wakeUp()
      1. 某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其它线程在第一个线程调用select()方法的那个对象上调用Selector.wakeup()方法即可。阻塞在select()方法上的线程会立马返回。
      2. 如果有其它线程调用了wakeup()方法,但当前没有线程阻塞在select()方法上,下个调用select()方法的线程会立即“醒来(wake up)”。
    2. close()
      1. 用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效。通道本身并不会关闭。

 

猜你喜欢

转载自blog.csdn.net/qq919694688/article/details/81705705