java nio selector理论总结

目录

阻塞与非阻塞

选择器简介

选择器的功能

创建选择器

向Selector注册通道

通过Selector选择通道

selectedKeys()

wakeUp()

close()

选择器常用方法

选择器使用小总结

SelectionKey

interest集合

ready集合

Channel + Selector

附加对象

代码示例

服务端

客户端


阻塞与非阻塞

传统的IO流都是阻塞式的。也就是说,当一个线程调用read()或write()时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此期间不能执行其他任务。因此,在完成网络通信进行IO操作时,由于线程会阻塞,所以服务器端必须为每个客户端都提供一个独立的线程进行处理,当服务器端需要处理大量客户端时,性能急剧下降。

Java NIO是非阻塞模式的。当线程从某通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。线程通常将非阻塞IO的空闲时间用于在其他通道上执行IO操作,所以单独的线程可以管理多个输入和输出通道。因此, NIO可以让服务器端使用一个或有限几个线程来同时处理连接到服务器端的所有客户端。

选择器简介

选择器(Selector) 是SelectableChannel对象的多路复用器, Selector可以同时监控多个SelectableChannel的IO状况,也就是说,利用Selector可使一个单独的线程管理多个Channel. Selector是非阻塞IO的核心。

类的结构如下

 Selector运行单线程处理多个Channel,如果你的应用打开了多个通道,但每个连接的流量都很低,使用Selector就会很方便。例如在一个聊天服务器中。要使用Selector, 得向Selector注册Channel,然后调用它的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新的连接进来、数据接收等。

通过调用Selector.open()方法创建一个Selector

Selector selector = Selector.open();

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

channel.configureBlocking(false);    //设置非阻塞

Selectionkey key = channel.register(selector,Selectionkey.OP_READ)

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

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

Connect 对应SelectionKey常量SelectionKey.OP_CONNECT

Accept 对应SelectionKey常量SelectionKey.OP_ACCEPT

Read 对应SelectionKey常量SelectionKey.OP_READ

Write 对应SelectionKey常量SelectionKey.OP_WRITE

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

选择器的功能

创建选择器

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

Selector selector = Selector.open();

向Selector注册通道

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

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

当调用registerl(Selector sel, int ops)将通道注册选择器时,选择器对通道的监听事件,需要通过第二个参数ops指定。

可以监听的事件类型(可使用SelectionKey的四个常量表示) :

读: SelectionKey.OP READ (1)

写: Selectionkey.OP WRITE (4)

连接: SelectionKey.OP CONNECT (8)

接收: SelectionKey.OP ACCEPT (16)

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

int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;

通过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)”中的就绪通道。如下所示:

Set selectedKeys = selector.selectedKeys(); 

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

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

                Set 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  
                      }  
                      keyIterator.remove();  
                } 

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

注意每次迭代末尾的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实例无效。通道本身并不会关闭。 

选择器常用方法

选择器使用小总结

1、创建Selector,

2、创建Channel,

3、向Selector中注册Channel及感兴趣的事件,

4.1、等待注册的事件到达,不然就一直等待 selector.select()

4.2、获取selector中选中项的迭代器,选中的项为注册的事件 Iterator ite = this.selector.selectedKeys().iterator();

4.3、针对选中的事件对感兴趣的事件进行处理。 

SelectionKey

Selectionkey:表示SelectableChannel和Selector之间的注册关系。每次向选择器注册通道时就会选择一个事件(选择键)。选择键包含两个表示为整数值的操作集。操作集的每一位都表示该键的通道所支持的一类可选择操作。

interest集合

interest集合是你所选择的感兴趣的事件集合。可以通过SelectionKey读写interest集合,像这样:

int interestSet = selectionKey.interestOps();
boolean isInterestedInAccept  = interestSet & SelectionKey.OP_ACCEPT;  
boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;  
boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;  
boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE; 

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

ready集合

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

int readySet = selectionKey.readyOps();

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

selectionKey.isAcceptable();  
selectionKey.isConnectable();  
selectionKey.isReadable();  
selectionKey.isWritable(); 

Channel + Selector

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

Channel  channel  = selectionKey.channel(); 
Selector selector = selectionKey.selector();

附加对象

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

selectionKey.attach(theObject);  
Object attachedObj = selectionKey.attachment(); 

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

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

代码示例

服务端

package com.anders.selector;  
  
import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.nio.ByteBuffer;  
import java.nio.channels.SelectableChannel;  
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 NIOServer {  
    // 通道管理器  
    private Selector selector;  
  
    public void initServer(int port) throws Exception {  
        // 获得一个ServerSocket通道  
        ServerSocketChannel serverChannel = ServerSocketChannel.open();  
        // 设置通道为 非阻塞  
        serverChannel.configureBlocking(false);  
        // 将该通道对于的serverSocket绑定到port端口  
        serverChannel.socket().bind(new InetSocketAddress(port));  
        // 获得一耳光通道管理器  
        this.selector = Selector.open();  
  
        // 将通道管理器和该通道绑定,并为该通道注册selectionKey.OP_ACCEPT事件  
        // 注册该事件后,当事件到达的时候,selector.select()会返回,  
        // 如果事件没有到达selector.select()会一直阻塞  
  
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);  
    }  
  
    // 采用轮训的方式监听selector上是否有需要处理的事件,如果有,进行处理  
    public void listen() throws Exception {  
        System.out.println("start server");  
        // 轮询访问selector  
        while (true) {  
            // 当注册事件到达时,方法返回,否则该方法会一直阻塞  
            selector.select();  
            // 获得selector中选中的相的迭代器,选中的相为注册的事件  
            Iterator ite = this.selector.selectedKeys().iterator();  
            while (ite.hasNext()) {  
                SelectionKey key = (SelectionKey) ite.next();  
                // 删除已选的key 以防重负处理  
                ite.remove();  
                // 客户端请求连接事件  
                if (key.isAcceptable()) {  
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();  
                    // 获得和客户端连接的通道  
                    SocketChannel channel = server.accept();  
                    // 设置成非阻塞  
                    channel.configureBlocking(false);  
                    // 在这里可以发送消息给客户端  
                    channel.write(ByteBuffer.wrap(new String("hello client").getBytes()));  
                    // 在客户端 连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限  
                    channel.register(this.selector, SelectionKey.OP_READ);  
                    // 获得了可读的事件  
  
                } else if (key.isReadable()) {  
                    read(key);  
                }  
  
            }  
        }  
    }  
  
    // 处理 读取客户端发来的信息事件  
    private void read(SelectionKey key) throws Exception {  
        // 服务器可读消息,得到事件发生的socket通道  
        SocketChannel channel = (SocketChannel) key.channel();  
        // 穿件读取的缓冲区  
        ByteBuffer buffer = ByteBuffer.allocate(10);  
        channel.read(buffer);  
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("server receive from client: " + msg);  
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());  
        channel.write(outBuffer);  
    }  
  
    public static void main(String[] args) throws Throwable {  
        NIOServer server = new NIOServer();  
        server.initServer(8989);  
        server.listen();  
    }  
} 

客户端

package com.anders.selector;  
  
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.SocketChannel;  
import java.util.Iterator;  
  
public class NIOClient {  
  
    // 通道管理器  
    private Selector selector;  
  
    /** 
     * * // 获得一个Socket通道,并对该通道做一些初始化的工作 * @param ip 连接的服务器的ip // * @param port 
     * 连接的服务器的端口号 * @throws IOException 
     */  
    public void initClient(String ip, int port) throws IOException { // 获得一个Socket通道  
        SocketChannel channel = SocketChannel.open(); // 设置通道为非阻塞  
        channel.configureBlocking(false); // 获得一个通道管理器  
        this.selector = Selector.open(); // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调  
        // 用channel.finishConnect();才能完成连接  
        channel.connect(new InetSocketAddress(ip, port));  
        // 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。  
        channel.register(selector, SelectionKey.OP_CONNECT);  
    }  
  
    /** 
     * * // 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 * @throws // IOException 
     * @throws Exception  
     */  
    @SuppressWarnings("unchecked")  
    public void listen() throws Exception { // 轮询访问selector  
        while (true) {  
            // 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,  
            // 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,  
            // selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的  
            selector.select(); // 获得selector中选中的项的迭代器  
            Iterator ite = this.selector.selectedKeys().iterator();  
            while (ite.hasNext()) {  
                SelectionKey key = (SelectionKey) ite.next(); // 删除已选的key,以防重复处理  
                ite.remove(); // 连接事件发生  
                if (key.isConnectable()) {  
                    SocketChannel channel = (SocketChannel) key.channel(); // 如果正在连接,则完成连接  
                    if (channel.isConnectionPending()) {  
                        channel.finishConnect();  
                    } // 设置成非阻塞  
                    channel.configureBlocking(false);  
                    // 在这里可以给服务端发送信息哦  
                    channel.write(ByteBuffer.wrap(new String("hello server!").getBytes()));  
                    // 在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。  
                    channel.register(this.selector, SelectionKey.OP_READ); // 获得了可读的事件  
                } else if (key.isReadable()) {  
                    read(key);  
                }  
            }  
        }  
    }  
  
    private void read(SelectionKey key) throws Exception {  
        SocketChannel channel = (SocketChannel) key.channel();  
        // 穿件读取的缓冲区  
        ByteBuffer buffer = ByteBuffer.allocate(10);  
        channel.read(buffer);  
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("client receive msg from server:" + msg);  
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());  
        channel.write(outBuffer);  
  
    }  
  
    /** 
     * * // 启动客户端测试 * @throws IOException 
     * @throws Exception  
     */  
    public static void main(String[] args) throws Exception {  
        NIOClient client = new NIOClient();  
        client.initClient("localhost", 8989);  
        client.listen();  
    }  
}  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值