4、NIO组件之Selector

  • 使用一个线程处理多个客户端连接,就会使用Selector
  • selector能够检测到多个注册的通道上是否有事件发生,如果有事件发生,获取事件针对每个事件进行相应的处理,就可以使用一个单线程去管理多个通道,即管理多个连接和请求;
  • 只有在连接真正有读写事件发生时,才会进行读写,大大地减少了系统开销;
  • 避免了多线程之间的上下文切换;

2、Selector介绍

说明

  • 当线程从某客户端socket通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。
  • 线程通常将非阻塞IO的空闲时间用于在其他通道上执行IO操作,单独的线程可以管理多个输入输出通道;
  • 由于读写操作都是非阻塞的,可以充分提高IO线程的允许效率,避免由于频繁IO阻塞导致的线程挂起。
  • 一个IO线程可以并发处理N个客户端的连接和读写操作,从根本上解决了传统同步阻塞IO的1连接1线程模型;

Selector类相关方法

//得到一个选择器对象
public static Selector open();
//检测所有注册的通道,当其中有IO操作可以进行时,将对应的
//SelectionKey加入到内部集合中并返回,参数用来设置超时时间
public abstract int select(long timeout);
//从内部集合中得到所有的SelectionKey
public abstract Set<SelectionKey> selectedKeys();
selector.select();//阻塞
selector.select(1000);//阻塞1000毫秒,在1000毫秒后返回
selector.wakeup();//唤醒selector
selector.selectNow();//不阻塞,立马返回

在这里插入图片描述

  • 当客户端进行连接时,通过ServerSocketChannel得到SocketChannel
  • Selector进行监听select方法,返回有事件发生的通道的个数
  • 将socketChannel注册到Selector上。register(Selector sel,int ops);
  • 注册后返回一个SelectionKey,会和该Selector关联;
  • 进一步得到各个SelectionKey;
  • 再通过SelectionKey反向获取SocketChannel;
  • 可以通过得到的channel完成业务处理;

3、实例

服务器端:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //1、创建ServerSocketChannel->ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个selector对象
        Selector selector = Selector.open();
        //绑定一个端口6666,在服务器监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);

        //将serverSocketChannel注册到selector,关心事件是OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待客户端连接
        while(true){
    
    
            //等待一秒,若没有事件发生,返回
            if(selector.select(1000)==0){
    
    
                System.out.println("服务器等待了1秒,无连接。。");
                continue;
            }

            //如果返回>0,表示已经获取到关注的事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            //遍历Set<SelectionKey>
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
    
    
                SelectionKey key = iterator.next();

                //如果发生了客户端连接
                if(key.isAcceptable()){
    
    
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功");
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                //如果发生了OP_READ
                if(key.isReadable()){
    
    
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer buffer = (ByteBuffer)key.attachment();
                    channel.read(buffer);
                    System.out.println("from client "+new String(buffer.array()));
                }
                iterator.remove();
            }
        }
    }
}

客户端:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
    
    
    public static void main(String[] args) throws IOException {
    
    
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        if(!socketChannel.connect(inetSocketAddress)){
    
    
            while(!socketChannel.finishConnect()){
    
    
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他工作");
            }
        }

        //连接成功
        String str="hello world";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据将buffer数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}

4、SelectionKey

表示Selector和网络通道的注册关系,

public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;

//得到与之关联的channel
public abstract SelectableChannel channel();
//得到与之关联的selector
public abstract Selector selector();
//是否可以accept
public final boolean isAcceptable();
public final boolean isReadable();
public final boolean isWritable();

5、ServerSocketChannel

  • 在服务器端监听新的客户端Socket连接

相关方法

//得到一个ServerSocketChannel通道
public static ServerSocketChannel open();
//设置服务器端端口号
public final ServerSocketChannel bind(SocketAddress local);
//设置阻塞模式/非阻塞模式
public final SelectableChannel configureBlocking(boolean block);
//接受一个连接
public SocketChannel accept();
//注册一个选择器并设置监听事件
public final SelectionKey register(Selector sel,int ops);

6、SocketChannel

public static SocketChannel open();
public final SelectableChannel configureBlocking(boolean block);
//连接服务器
public boolean connect(SocketAddress remote);
//若是上面的失败,就要通过该方法完成连接操作
public boolean finishConnect();
//从通道中读数据
public int read(ByteBuffer dst);
//往通道中写数据
public int write(ByteBuffer src);
public final SelectionKey register(Selector sel,int ops,Object att);
public final void close();

猜你喜欢

转载自blog.csdn.net/qq_37935909/article/details/109034611