从Java NIO到Netty(四)

268 阅读1分钟

Java NIO总结

结合前三章所讲,现在我们整合代码变为如下,以便对Java NIO的组件有个清楚的认识:

public static void main(String[] args) throws Exception {

        //打开ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //监听端口9999
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        //设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //创建Selector
        Selector selector = Selector.open();
        //将选serverSocketChannel注册到selector,并在注册过程中指出该serverSocketChannel可以进行Accept操作
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true)
        {
            int selectInt = selector.selectNow();
            if (selectInt == 0) {
                continue;
            }
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while (keyIterator.hasNext())
            {
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()) {
                    ServerSocketChannel ServerSocketChannel = (ServerSocketChannel)key.channel();
                    //创建SocketChannel
                    SocketChannel clientChannel = ServerSocketChannel.accept();
                    //设置为非阻塞式
                    clientChannel.configureBlocking(false);
                    //注册到selector
                    clientChannel.register(key.selector(), SelectionKey.OP_READ);
                } else if (key.isConnectable()) {
                    // a connection was established with a remote server.
                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 将SocketChannel的数据读到buffer中
                    ByteBuffer buf = ByteBuffer.allocate(2048);
                    int bytesRead = channel.read(buf);
                } else if (key.isWritable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    //将buffer的数据写入SocketChannel
                    String newData = "hello world";
                    //Buffer操作后面章节介绍
                    ByteBuffer buf = ByteBuffer.allocate(2048);
                    buf.clear();
                    buf.put(newData.getBytes());
                    buf.flip();
                    while(buf.hasRemaining()) {
                        channel.write(buf);
                    }
                }
                keyIterator.remove();
            }
        }
    }

以上就是整个Java NIO的内容,需要注意的是,我只是介绍了跟Netty相关和可以进行对比的三个组件,Java NIO的组件和内容不止于此。