【超详细解释】从Java NIO到Netty的每一步 (四)

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的组件和内容不止于此。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛战士从不脱下面具

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值