NIO系列4:Selector的理解

本文参考至:http://ifeve.com/selectors/

Selector(选择器):

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

下面通过介绍几个方法来理解Selector于channel是怎样使用的:

Selector的open():

用来创建Selector对象

SelectableChannel的register(Selector sel, int ops)方法:

SelectableChannel是一个抽象类,凡是继承了它的类都可以切换阻塞状态(由非阻塞状态变为阻塞状态或者由阻塞状态变为非阻塞状态)典型的例子就是ServerSocketChannel(后面的实例就是用到它),我之前例子中用到的FileChannel它的状态是无法切换到非阻塞状态的。
方法中的第一个参数Selector sel表示channel要注册到的Selector,第二个参数int ops表示:在通过Selector监听Channel时对什么事件感兴趣。可以监听四种不同类型的事件:
1、Connect(通道触发了一个事件,意思是该事件已经就绪。某个channel成功连接到另一个服务器称为“连接就绪”。);
2、Accept(一个server socket channel准备好接收新进入的连接称为“接收就绪”。);
3、Read(一个有数据可读的通道可以说是“读就绪”。);
4、Write(等待写数据的通道可以说是“写就绪”。)

上面的这四种事件用SelectionKey的四个常量来表示:
SelectionKey.OP_CONNECT
SelectionKey.OP_ACCEPT
SelectionKey.OP_READ
SelectionKey.OP_WRITE

根据上面的描述简单来段代码:

        socketChannel = ServerSocketChannel.open();
        // 调整socketChannel通道的阻塞情况,传参为false表示将这个通道设置为非阻塞
        socketChannel.configureBlocking(false);
        System.out.println("listener on port:" + port);
        selector = Selector.open();
        // 表示将通道注册到Selector中
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

下面是模拟客户端向服务端的请求:
服务端:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * ServerSocketChannelTest:服务端
 * ServerSocketChannelTest(服务端)和SocketChannelTest(客户端)是一个简单的服务器
* 这个代码结合ServerSocketChannel来演示Selector的使用 * * @author JM * @2017-3-24 */ public class ServerSocketChannelTest { private int size = 1024; private ServerSocketChannel socketChannel; private ByteBuffer byteBuffer; private Selector selector; /** 端口号 */ private final int port = 8998; /** 客户端访问数量 */ private int remoteClientNum = 0; public ServerSocketChannelTest() { try { initChannel(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } public void initChannel() throws Exception { socketChannel = ServerSocketChannel.open(); // 调整socketChannel通道的阻塞情况,传参为false表示将这个通道设置为非阻塞 socketChannel.configureBlocking(false); // InetSocketAddress对象表示IP Socket Address(IP号+端口号)就是访问路径 // bind(SocketAddress local)方法表示:Binds the channel's socket to a local // address and configures the socket to listen for connections. // 就是对这个IP Socket Address进行绑定监听 socketChannel.bind(new InetSocketAddress(port)); System.out.println("listener on port:" + port); selector = Selector.open(); // 表示将通道注册到Selector中 socketChannel.register(selector, SelectionKey.OP_ACCEPT); byteBuffer = ByteBuffer.allocate(size); byteBuffer.order(ByteOrder.BIG_ENDIAN); } private void listener() throws Exception { while (true) { System.out.println("------------------1"); int n = selector.select(); System.out.println("------------------4"); if (n == 0) { continue; } Iterator ite = selector.selectedKeys().iterator(); while (ite.hasNext()) { SelectionKey key = ite.next(); if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); remoteClientNum++; System.out.println("online client num = " + remoteClientNum); replyClient(channel); } if (key.isReadable()) { readDataFromSocket(key); } ite.remove(); } } } protected void readDataFromSocket(SelectionKey key) throws Exception { SocketChannel socketChannel = (SocketChannel) key.channel(); int count; byteBuffer.clear(); while ((count = socketChannel.read(byteBuffer)) > 0) { byteBuffer.flip(); while (byteBuffer.hasRemaining()) { socketChannel.write(byteBuffer); } byteBuffer.clear(); } if (count < 0) { socketChannel.close(); } } private void replyClient(SocketChannel channel) throws IOException { byteBuffer.clear(); byteBuffer.put("hello client!\r\n".getBytes()); byteBuffer.flip(); channel.write(byteBuffer); } public static void main(String[] args) { try { new ServerSocketChannelTest().listener(); } catch (Exception e) { } } }

客户端:

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

public class SocketChannelTest {
    private int size = 1024;
    private ByteBuffer byteBuffer;
    private SocketChannel socketChannel;

    /**
     * 将通道连接服务器
     * @throws IOException
     */
    public void connectServer() throws IOException {
        socketChannel = SocketChannel.open();
        // 将这个channel连接到服务器上(IP+port)
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8998));
        //初始化缓冲区大小
        byteBuffer = ByteBuffer.allocate(size);
        //定义byteBuffer从缓冲区中存储或检索多字节数值时使用哪一字节顺序的常量
        //ByteOrder:作用就像一个类型安全的枚举。它定义了以其本身实例预初始化的两个public区域。
        //只有这两个ByteOrder实例总是存在于JVM中,因此它们可以通过使用--操作符进行比较
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
        receive();
    }

    /**
     * 接收来自服务器的消息
     * @throws IOException
     */
    private void receive() throws IOException {
        while (true) {
            byteBuffer.clear();
            while (socketChannel.read(byteBuffer) > 0) {
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()) {
                    System.out.print((char) byteBuffer.get());
                }
                send("send data to server\r\n".getBytes());
                byteBuffer.clear();
            }
        }
    }

    private void send(byte[] data) throws IOException {
        byteBuffer.clear();
        byteBuffer.put(data);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
    }

    public static void main(String[] args) throws IOException {
        new SocketChannelTest().connectServer();
    }
}

本来还想介绍一下SocketChannel的,不过文章篇幅太长。下篇再介绍。

你可能感兴趣的:(NIO系列4:Selector的理解)