Selector选择器

1 基本介绍

  1. java中的nio,用非阻塞的IO方式。可以用一个线程,处理多个客户端连接,就会使用到Selector选择器

  1. Selector能够检测多个注册的通道上是否有事件发生(注意:多个Channle以事件的方式可以注册到同一个Selector),如果有事件发生获取事件然后针对每个事件进行相应的处理,这样就可以用一个单线程管理多个通道,也就是管理多个连接和请求。

  1. 只有在连接有多个读写事件发生时,才会进行读写,就大大减少了系统的开销,并且不会为每个连接都创建一个线程,不用去维护多个线程

  1. 避免了多线程之间上下文切换导致的开销。

特点说明:

  1. Netty的IO线程NioEventLoop聚合了Selector选择器,也叫多路复用器,可以同时处理成百上千条请求。

  1. 当线程从某客户端Socket通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务

  1. 线程通常将非阻塞的IO的空闲线程用在其它通道执行IO操作,所以单独的线程可以管理多个输入和输出通道

  1. 由于读写操作都是非阻塞的,这就可以充分提升IO线程的运行效率,避免由于频繁I/O阻塞导致线程挂起

  1. 一个I/O线程可以并发处理N个客户端连接和读写数据操作,这从根本上解决了传统同步阻塞I/O一连接一线程模型。

2 使用方法

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

Selector open = Selector.open();

2.注册channel到Selector

socketChannel.configureBlocking(false);
final SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);

注意:注册的channel必须是非阻塞的(FileChannel不适用于Selector,因为FileChannel不能切换为非阻塞模式)

register()方法的第二个参数,是通过Selector监听Channel对什么事件感兴趣

Connect : 某个 Channel 成功连接到另一个服务器称为"连接就绪", SelectionKey.OP_CONNECT
Accept : 一个 ServerSocketChannel 准备好接受新进入的连接称为"接受就绪", SelectionKey.OP_ACCEPT
Read : 一个有数据可读的 Channel 称为"读就绪", SelectionKey.OP_READ
Write : 等待写数据的 Channel 称为"写就绪", SelectionKey.OP_WRITE

如果不止对一件事情感兴趣,可以用操作符将其连接起来如下:

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

总结:

  1. 创建Selector

     // 获得一耳光通道管理器
        Selector selector = Selector.open();
  1. 创建Channel

        // 获得一个ServerSocket通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
  1. 向Selector中注册Channel,和感兴趣的事情

       // 将通道管理器和该通道绑定,并为该通道注册selectionKey.OP_ACCEPT事件
        // 注册该事件后,当事件到达的时候,selector.select()会返回,
        // 如果事件没有到达selector.select()会一直阻塞

        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
  1. 等待注册事件的到达,不然就一直等待selector.select()

            // 当注册事件到达时,方法返回,否则该方法会一直阻塞
            selector.select();
  1. 获取selector中的迭代器,选中的项为注册的事件

  1. 针对选中的事件进行处理

3 SelectionKey介绍

selectionKey表示了一个特定的channel对象和一个特定的Selector对象之间的注册关系

key.channel(); // 返回该SelectionKey对应的channel。
key.selector(); // 返回该SelectionKey对应的Selector。
key.interestOps(); //返回代表需要Selector监控的IO操作的bit mask

4代码演示

服务端:

package com.liubujun.nio.groupchat;

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;

/**
 * @Author: liubujun
 * @Date: 2023/2/1 16:01
 */


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.liubujun.nio.groupchat;

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;

/**
 * @Author: liubujun
 * @Date: 2023/2/1 16:03
 */


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();
    }
}

参考博客:https://blog.csdn.net/lw305080/article/details/51205545?

posted @ 2023-01-29 16:00  小猪不会叫  阅读(75)  评论(0)    收藏  举报  来源