- NIO算是实现Reactor设计模式(单Selector 单工作线程)
- 底层window用的是select,linux用的是epoll
网络NIO代码实现:
public NIOServer(int port) throws Exception {selector = Selector.open();serverSocket = ServerSocketChannel.open();serverSocket.socket().bind(new InetSocketAddress(port));serverSocket.configureBlocking(false);serverSocket.register(selector, SelectionKey.OP_ACCEPT);}@Overridepublic void run() {while (!Thread.interrupted()) {try {//阻塞等待事件selector.select();// 事件列表Set selected = selector.selectedKeys();Iterator it = selected.iterator();while (it.hasNext()) {it.remove();//分发事件dispatch((SelectionKey) (it.next()));}} catch (Exception e) {}}}private void dispatch(SelectionKey key) throws Exception {if (key.isAcceptable()) {register(key);//新链接建立,注册} else if (key.isReadable()) {read(key);//读事件处理} else if (key.isWritable()) {wirete(key);//写事件处理}}private void register(SelectionKey key) throws Exception {ServerSocketChannel server = (ServerSocketChannel) key.channel();// 获得和客户端连接的通道SocketChannel channel = server.accept();channel.configureBlocking(false);//客户端通道注册到selector 上channel.register(this.selector, SelectionKey.OP_READ);}
- 将server端io注册到 Selector(相当于Reactor模式的Reactor)
- Selector去轮询(阻塞),
- 当Selector.select 有返回的时候,说明有数据了,遍历socket,根据事件的不同类型 分给不同的事件处理器执行