• Netty中BIO,NIO


    同步阻塞io(BIO)、伪异步io(PIO)、非阻塞io(NIO)、异步io(AIO)的概念及区别?

    同步阻塞io(BIO):服务器端与客户端通过三次握手后建立连接,连接成功,双方通过I/O进行同步阻塞式通信。

    弊端:1,读和写操作是同步阻塞的,任何一端出现网络性能问题,都会影响另一方。2,一个链路建立一个线程,无法满足高并发,高性能需求。

    伪异步io(PIO):为了解决同步阻塞式IO一个链路建立一个线程的弊端,出现了伪异步IO,伪异步IO其实就是通过线程池/队列来处理多个客户端的接入,通过线程池可以灵活的调配线程资源,设置线程最大值,防止海量并发接入导致线程耗尽。

    弊端:1,读和写操作是同步阻塞的,任何一端出现网络性能问题,都会影响另一方

    非阻塞io(NIO):nio类库是jdk1.4中引入的,它弥补了同步阻塞IO的不足,它在Java提供了高速的,面向块的I/O。同步阻塞IO是以流的方式处理数据,而NIO是以块的方式处理数据。面向流的I/O通常比较慢, 按块处理数据比按(流式的)字节处理数据要快得多。

    异步非阻塞io(AIO):NIO2的异步套接字通道时真正的异步非阻塞I/O,它对应unix网络驱动中的事件驱动I/O,它不需要通过多路复用器对注册的通道进行轮询操作即可实现异步读写,简化了NIO编程模型。

    代码:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.ClosedChannelException;
    import java.nio.channels.Selector;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * Created by Administrator on 2016/12/24 0024.
     */
    public class Processor {
        private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class);
        private static final ExecutorService service =
                Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());
        private Selector selector;
        public Processor() throws IOException {
            this.selector = SelectorProvider.provider().openSelector();
            start();
        }
        public void addChannel(SocketChannel socketChannel) throws ClosedChannelException {
            socketChannel.register(this.selector, SelectionKey.OP_READ);
        }
        public void start() {
            service.submit(() -> {
                while (true) {
                    if (selector.selectNow() <= 0) {
                        continue;
                    }
                    Set<SelectionKey> keys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            SocketChannel socketChannel = (SocketChannel) key.channel();
                            int count = socketChannel.read(buffer);
                            if (count < 0) {
                                socketChannel.close();
                                key.cancel();
                                LOGGER.info("{}	 Read ended", socketChannel);
                                continue;
                            } else if (count == 0) {
                                LOGGER.info("{}	 Message size is 0", socketChannel);
                                continue;
                            } else {
                                LOGGER.info("{}	 Read message {}", socketChannel, new String(buffer.array()));
                            }
                        }
                    }
                }
            });
        }
    }

    NIOServer:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Set;
    
    /**
     * Created by Administrator on 2016/12/23 0023.
     */
    
    public class NIOServer {
        private static final Logger LOGGER = LoggerFactory.getLogger(NIOServer.class);
        public static void main(String[] args) throws IOException {
            Selector selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(1234));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            int coreNum = Runtime.getRuntime().availableProcessors();
            Processor[] processors = new Processor[coreNum];
            for (int i = 0; i < processors.length; i++) {
                processors[i] = new Processor();
            }
            int index = 0;
            while (selector.select() > 0) {
                Set<SelectionKey> keys = selector.selectedKeys();
                for (SelectionKey key : keys) {
                    keys.remove(key);
                    if (key.isAcceptable()) {
                        ServerSocketChannel acceptServerSocketChannel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = acceptServerSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        LOGGER.info("Accept request from {}", socketChannel.getRemoteAddress());
                        Processor processor = processors[(int) ((index++) / coreNum)];
                        processor.addChannel(socketChannel);
                    }
                }
            }
        }
    }

    http://blog.csdn.net/kevinxxw/article/details/47837361

    http://www.jasongj.com/java/nio_reactor/

    http://ifeve.com/netty-in-action/

  • 相关阅读:
    [Typescript Challenges] 1. Easy Pick
    [Typescript Challenges] 5. Easy Length of Tuple
    AcWing 903. 昂贵的聘礼
    AcWing 1126. 最小花费
    AcWing 1127 香甜的黄油
    AcWing 1128. 信使
    AcWing 340. 通信线路
    AcWing 920. 最优乘车
    AcWing 1135. 新年好
    当你不再需要通过别人的认可来证明自己的时候,你就真的强大了。
  • 原文地址:https://www.cnblogs.com/hongdada/p/6056231.html
Copyright © 2020-2023  润新知