Java NIO summary

As described in the previous three chapters, we now consolidate the code as follows to get a clear idea of the Java NIO components:

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

        / / open the ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // Listen on port 9999
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        // Set to non-blocking mode
        serverSocketChannel.configureBlocking(false);
        / / create the Selector
        Selector selector = Selector.open();
        // Register the selector serverSocketChannel with the Selector and indicate during the registration that the serverSocketChannel can 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();
                    / / create a SocketChannel
                    SocketChannel clientChannel = ServerSocketChannel.accept();
                    // Set it to non-blocking
                    clientChannel.configureBlocking(false);
                    // Register 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();
                    // Read SocketChannel data into buffer
                    ByteBuffer buf = ByteBuffer.allocate(2048);
                    int bytesRead = channel.read(buf);
                } else if (key.isWritable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // Write buffer data to SocketChannel
                    String newData = "hello world";
                    // The Buffer operation is described in the following sections
                    ByteBuffer buf = ByteBuffer.allocate(2048);
                    buf.clear();
                    buf.put(newData.getBytes());
                    buf.flip();
                    while(buf.hasRemaining()) { channel.write(buf); } } keyIterator.remove(); }}}Copy the code

That’s all there is to Java NIO. It’s important to note that I’ve only introduced three components related to And comparable to Netty. There are more components and content in Java NIO.