JAVA nio selector 入门

2016/01/14 19:36
阅读数 365

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

 

为什么使用Selector?

 

仅用单个线程来处理多个Channels的好处是,只需要更少的线程来处理通道。事实上,可以只用一个线程处理所有的通道。对于操作系统来说,线程之间上下文切换的开销很大,而且每个线程都要占用系统的一些资源(如内存)。因此,使用的线程越少越好。

 

但是,需要记住,现代的操作系统和CPU在多任务方面表现的越来越好,所以多线程的开销随着时间的推移,变得越来越小了。实际上,如果一个CPU有多个内核,不使用多任务可能是在浪费CPU能力。不管怎么说,关于那种设计的讨论应该放在另一篇不同的文章中。在这里,只要知道使用Selector能够处理多个通道就足够了。

 

Selector的创建

通过调用Selector.open()方法创建一个Selector,如下:

Java代码  收藏代码

  1. Selector selector = Selector.open();  

 

向Selector注册通道

为了将Channel和Selector配合使用,必须将channel注册到selector上。通过SelectableChannel.register()方法来实现,如下:

 

Java代码  收藏代码

  1. channel.configureBlocking(false);  

  2. SelectionKey key = channel.register(selector, Selectionkey.OP_READ);  

 

与Selector一起使用时,Channel必须处于非阻塞模式下。这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。

 

注意register()方法的第二个参数。这是一个“interest集合”,意思是在通过Selector监听Channel时对什么事件感兴趣。可以监听四种不同类型的事件:

Connect

Accept

Read

Write

 

通道触发了一个事件意思是该事件已经就绪。所以,某个channel成功连接到另一个服务器称为“连接就绪”。一个server socket channel准备好接收新进入的连接称为“接收就绪”。一个有数据可读的通道可以说是“读就绪”。等待写数据的通道可以说是“写就绪”。

这四种事件用SelectionKey的四个常量来表示:

Java代码  收藏代码

  1. SelectionKey.OP_CONNECT  

  2. SelectionKey.OP_ACCEPT  

  3. SelectionKey.OP_READ  

  4. SelectionKey.OP_WRITE  

 

如果你对不止一种事件感兴趣,那么可以用“位或”操作符将常量连接起来,如下:

Java代码  收藏代码

  1. int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;  

 

当向Selector注册Channel时,register()方法会返回一个SelectionKey对象。这个对象包含了一些你感兴趣的属性:

 

interest集合

ready集合

Channel

Selector

附加的对象(可选)

 

下面我会描述这些属性。

 

interest集合

 

就像向Selector注册通道一节中所描述的,interest集合是你所选择的感兴趣的事件集合。可以通过SelectionKey读写interest集合,像这样:

Java代码  收藏代码

  1. int interestSet = selectionKey.interestOps();  

  2. boolean isInterestedInAccept  = interestSet & SelectionKey.OP_ACCEPT;  

  3. boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;  

  4. boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;  

  5. boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE;   

 可以看到,用“位与”操作interest 集合和给定的SelectionKey常量,可以确定某个确定的事件是否在interest 集合中。

 

ready集合

 

ready 集合是通道已经准备就绪的操作的集合。在一次选择(Selection)之后,你会首先访问这个ready set。Selection将在下一小节进行解释。可以这样访问ready集合:

Java代码  收藏代码

  1. int readySet = selectionKey.readyOps();  

 

可以用像检测interest集合那样的方法,来检测channel中什么事件或操作已经就绪。但是,也可以使用以下四个方法,它们都会返回一个布尔类型:

Java代码  收藏代码

  1. selectionKey.isAcceptable();  

  2. selectionKey.isConnectable();  

  3. selectionKey.isReadable();  

  4. selectionKey.isWritable();  

 

Channel + Selector

 

从SelectionKey访问Channel和Selector很简单。如下:

 

Java代码  收藏代码

  1. Channel  channel  = selectionKey.channel();  

  2. Selector selector = selectionKey.selector();  

 

附加的对象

 

可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:

Java代码  收藏代码

  1. selectionKey.attach(theObject);  

  2. Object attachedObj = selectionKey.attachment();  

 

还可以在用register()方法向Selector注册Channel的时候附加对象。如:

Java代码  收藏代码

  1. SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);  

 

通过Selector选择通道

 

一旦向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()方法,访问“已选择键集(selected key set)”中的就绪通道。如下所示:

Java代码  收藏代码

  1. Set selectedKeys = selector.selectedKeys();  

 

当像Selector注册Channel时,Channel.register()方法会返回一个SelectionKey 对象。这个对象代表了注册到该Selector的通道。可以通过SelectionKey的selectedKeySet()方法访问这些对象。

可以遍历这个已选择的键集合来访问就绪的通道。如下:

Java代码  收藏代码

  1. Set selectedKeys = selector.selectedKeys();  

  2. Iterator keyIterator = selectedKeys.iterator();  

  3. while(keyIterator.hasNext()) {  

  4.     SelectionKey key = keyIterator.next();  

  5.     if(key.isAcceptable()) {  

  6.         // a connection was accepted by a ServerSocketChannel.  

  7.     } else if (key.isConnectable()) {  

  8.         // a connection was established with a remote server.  

  9.     } else if (key.isReadable()) {  

  10.         // a channel is ready for reading  

  11.     } else if (key.isWritable()) {  

  12.         // a channel is ready for writing  

  13.     }  

  14.     keyIterator.remove();  

  15. }  

 

这个循环遍历已选择键集中的每个键,并检测各个键所对应的通道的就绪事件。

 

注意每次迭代末尾的keyIterator.remove()调用。Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中

 

SelectionKey.channel()方法返回的通道需要转型成你要处理的类型,如ServerSocketChannel或SocketChannel等。

 

wakeUp()

 

某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其它线程在第一个线程调用select()方法的那个对象上调用Selector.wakeup()方法即可。阻塞在select()方法上的线程会立马返回。

 

如果有其它线程调用了wakeup()方法,但当前没有线程阻塞在select()方法上,下个调用select()方法的线程会立即“醒来(wake up)”。

 

close()

 

用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效。通道本身并不会关闭。

 

 

----------------------------------------------------------------------------------------------------

下面的例子是当客户端发送的字符串,server端接收并打印,然后将接收的字符串反馈给client

 

server端代码

Java代码  收藏代码

  1. package hb.server;  

  2.   

  3. import java.io.*;  

  4. import java.nio.*;  

  5. import java.nio.channels.*;  

  6. import java.nio.channels.spi.*;  

  7. import java.net.*;  

  8. import java.util.*;  

  9. import java.nio.charset.*;  

  10.   

  11. public class NServer {  

  12.     // 用于检测所有Channel状态的Selector  

  13.     private Selector selector = null;  

  14.     // 定义实现编码、解码的字符集对象  

  15.     private Charset charset = Charset.forName("UTF-8");  

  16.   

  17.     public void init() throws IOException {  

  18.         selector = Selector.open();  

  19.         // 通过open方法来打开一个未绑定的ServerSocketChannel实例  

  20.         ServerSocketChannel server = ServerSocketChannel.open();  

  21.         InetSocketAddress isa = new InetSocketAddress("127.0.0.1"30000);  

  22.         // 将该ServerSocketChannel绑定到指定IP地址  

  23.         server.socket().bind(isa);  

  24.         // 设置ServerSocket以非阻塞方式工作  

  25.         server.configureBlocking(false);  

  26.         // 将server注册到指定Selector对象  

  27.         server.register(selector, SelectionKey.OP_ACCEPT);  

  28.         while (selector.select() > 0) {  

  29.             // 依次处理selector上的每个已选择的SelectionKey  

  30.             for (SelectionKey sk : selector.selectedKeys()) {  

  31.                 // 从selector上的已选择Key集中删除正在处理的SelectionKey  

  32.                 selector.selectedKeys().remove(sk);  

  33.                 // 如果sk对应的通道包含客户端的连接请求  

  34.                 if (sk.isAcceptable()) {  

  35.                     // 调用accept方法接受连接,产生服务器端对应的SocketChannel  

  36.                     SocketChannel sc = server.accept();  

  37.                     // 设置采用非阻塞模式  

  38.                     sc.configureBlocking(false);  

  39.                     // 将该SocketChannel也注册到selector  

  40.                     sc.register(selector, SelectionKey.OP_READ);  

  41.                     // 将sk对应的Channel设置成准备接受其他请求  

  42.                     sk.interestOps(SelectionKey.OP_ACCEPT);  

  43.                 }  

  44.                 // 如果sk对应的通道有数据需要读取  

  45.                 if (sk.isReadable()) {  

  46.                     // 获取该SelectionKey对应的Channel,该Channel中有可读的数据  

  47.                     SocketChannel sc = (SocketChannel) sk.channel();  

  48.                     // 定义准备执行读取数据的ByteBuffer  

  49.                     ByteBuffer buff = ByteBuffer.allocate(1024);  

  50.                     String content = "";  

  51.                     // 开始读取数据  

  52.                     try {  

  53.                         while (sc.read(buff) > 0) {  

  54.                             buff.flip();  

  55.                             content += charset.decode(buff);  

  56.                         }  

  57.                         // 打印从该sk对应的Channel里读取到的数据  

  58.                         System.out.println("=====" + content);  

  59.                         // 将sk对应的Channel设置成准备下一次读取  

  60.                         sk.interestOps(SelectionKey.OP_READ);  

  61.                     }  

  62.                     // 如果捕捉到该sk对应的Channel出现了异常,即表明该Channel  

  63.                     // 对应的Client出现了问题,所以从Selector中取消sk的注册  

  64.                     catch (IOException ex) {  

  65.                         // 从Selector中删除指定的SelectionKey  

  66.                         sk.cancel();  

  67.                         if (sk.channel() != null) {  

  68.                             sk.channel().close();  

  69.                         }  

  70.                     }  

  71.                     // 如果content的长度大于0,即聊天信息不为空  

  72.                     if (content.length() > 0) {  

  73.                         // 遍历该selector里注册的所有SelectKey  

  74.                         for (SelectionKey key : selector.keys()) {  

  75.                             // 获取该key对应的Channel  

  76.                             Channel targetChannel = key.channel();  

  77.                             // 如果该channel是SocketChannel对象  

  78.                             if (targetChannel instanceof SocketChannel) {  

  79.                                 // 将读到的内容写入该Channel中  

  80.                                 SocketChannel dest = (SocketChannel) targetChannel;  

  81.                                 dest.write(charset.encode(content));  

  82.                             }  

  83.                         }  

  84.                     }  

  85.                 }  

  86.             }  

  87.         }  

  88.     }  

  89.   

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

  91.         new NServer().init();  

  92.     }  

  93. }  

 

客户端

Java代码  收藏代码

  1. package hb.server;  

  2.   

  3. import java.io.*;  

  4. import java.net.*;  

  5. import java.nio.*;  

  6. import java.nio.channels.*;  

  7. import java.nio.charset.*;  

  8. import java.util.*;  

  9.   

  10. public class NClient  

  11. {  

  12.     //定义检测SocketChannel的Selector对象  

  13.     private Selector selector = null;  

  14.     //定义处理编码和解码的字符集  

  15.     private Charset charset = Charset.forName("UTF-8");  

  16.     //客户端SocketChannel  

  17.     private SocketChannel sc = null;  

  18.     public void init()throws IOException  

  19.     {  

  20.         selector = Selector.open();  

  21.         InetSocketAddress isa = new InetSocketAddress("127.0.0.1"30000);  

  22.         //调用open静态方法创建连接到指定主机的SocketChannel  

  23.         sc = SocketChannel.open(isa);  

  24.         //设置该sc以非阻塞方式工作  

  25.         sc.configureBlocking(false);  

  26.         //将SocketChannel对象注册到指定Selector  

  27.         sc.register(selector, SelectionKey.OP_READ);  

  28.         //启动读取服务器端数据的线程  

  29.         new ClientThread().start();  

  30.         //创建键盘输入流  

  31.         Scanner scan = new Scanner(System.in);  

  32.         while (scan.hasNextLine())  

  33.         {  

  34.             //读取键盘输入  

  35.             String line = scan.nextLine();  

  36.             //将键盘输入的内容输出到SocketChannel中  

  37.             sc.write(charset.encode(line));  

  38.         }  

  39.     }  

  40.     //定义读取服务器数据的线程  

  41.     private class ClientThread extends Thread  

  42.     {  

  43.         public void run()  

  44.         {  

  45.             try  

  46.             {  

  47.                 while (selector.select() > 0)   

  48.                 {  

  49.                     //遍历每个有可用IO操作Channel对应的SelectionKey  

  50.                     for (SelectionKey sk : selector.selectedKeys())  

  51.                     {  

  52.                         //删除正在处理的SelectionKey  

  53.                         selector.selectedKeys().remove(sk);  

  54.                         //如果该SelectionKey对应的Channel中有可读的数据  

  55.                         if (sk.isReadable())  

  56.                         {  

  57.                             //使用NIO读取Channel中的数据  

  58.                             SocketChannel sc = (SocketChannel)sk.channel();  

  59.                             ByteBuffer buff = ByteBuffer.allocate(1024);  

  60.                             String content = "";  

  61.                             while(sc.read(buff) > 0)  

  62.                             {  

  63.                                 sc.read(buff);   

  64.                                 buff.flip();  

  65.                                 content += charset.decode(buff);  

  66.                             }  

  67.                             //打印输出读取的内容  

  68.                             System.out.println("聊天信息:" + content);  

  69.                             //为下一次读取作准备  

  70.                             sk.interestOps(SelectionKey.OP_READ);  

  71.                         }  

  72.                     }  

  73.                 }  

  74.             }  

  75.             catch (IOException ex)  

  76.             {  

  77.                 ex.printStackTrace();  

  78.             }  

  79.         }  

  80.     }  

  81.   

  82.     public static void main(String[] args)  

  83.         throws IOException  

  84.     {  

  85.         new NClient().init();  

  86.     }  

  87. }  


展开阅读全文
加载中
点击加入讨论🔥(1) 发布并加入讨论🔥
打赏
1 评论
9 收藏
1
分享
返回顶部
顶部