深入分析JAVA WEB技术内幕(二)

JAVA NIO概述

NIO的工作机制
  1. channel和selector的概念在NIO中尤为突出。channel可比喻为汽车或者高铁,selector则是车站的调度系统,负责控制每个车的运行状态。
public void selector() throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false); // 设置为非阻塞方式
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 注册监听事件
        while(true) {
            Set selectKeys = selector.selectedKeys();
            Iterator iterator = selectKeys.iterator();
            while(iterator.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) iterator.next();
                if ((selectionKey.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                    ServerSocketChannel sscChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel sc = sscChannel.accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                    iterator.remove();
                } else if ((selectionKey.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                    SocketChannel sc = (SocketChannel) selectionKey.channel();
                    while(true) {
                        buffer.clear();
                        int i = sc.read(buffer);
                        if (i < 0) {
                            break;
                        }
                        buffer.flip();
                    }
                    iterator.remove();
                }
            }
        }
    }

你可能感兴趣的:(深入分析JAVA WEB技术内幕(二))