Java IO系列之四:NIO通訊模型 Java NIO系列教程(一) Java NIO 概述 java nio詳解

分佈式rpc框架有不少,好比dubbo,netty,還有不少其餘的產品。但他們大部分都是基於nio的,html

nio是非阻塞的io,那麼它的內部機制是怎麼實現的呢。java

1.由一個專門的線程處理全部IO事件,並負責分發。spring

2.事件驅動機制,事件到來的時候觸發操做,不須要阻塞的監視事件。緩存

3.線程以前經過wait,notify通訊,減小線程切換。網絡

 

NIO使用步驟

服務端步驟:session

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        new Thread(new ReactorTask()).start();
    }

    public static class ReactorTask implements Runnable {
        private Selector selector;
        public ReactorTask() {
            try {
                // 第一步:打開ServerSocketChannel,用於監聽客戶端的鏈接,它是全部客戶端鏈接的父管道
                ServerSocketChannel acceptorSvr = ServerSocketChannel.open();

                // 第二步:綁定監聽端口,設置鏈接爲非阻塞模式
                acceptorSvr.socket().bind(new InetSocketAddress(InetAddress.getByName("localhost"), 1234));
                acceptorSvr.configureBlocking(false);

                // 第三步:建立Reactor線程,建立多路複用器並啓動線程
                selector = Selector.open();

                // 第四步:將ServerSocketChannel註冊到Reactor線程的多路複用器Selector上,監聽Accept事件
                SelectionKey key = acceptorSvr.register(selector, SelectionKey.OP_ACCEPT);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            // 第五步:在run方法中無限循環體內輪詢準備就緒的Key
            while (true) {
                try {
                    selector.select(1000);
                    Set<SelectionKey> selectedKeys = selector.selectedKeys();
                    Iterator<SelectionKey> it = selectedKeys.iterator();
                    SelectionKey key = null;
                    while (it.hasNext()) {
                        key = it.next();
                        it.remove();
                        try {
                            if (key.isValid()) {
                                // 處理新接入的請求消息
                                if (key.isAcceptable()) {
                                    // 第六步:多路複用器監聽到有新的客戶端接入,處理新的接入請求,完成TCP三次握手,創建物理鏈路
                                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                                    SocketChannel sc = ssc.accept();
                                    // 第七步:設置客戶端鏈路爲非阻塞模式
                                    sc.configureBlocking(false);
                                    sc.socket().setReuseAddress(true);
                                    // 第八步:將新接入的客戶端鏈接註冊到Reactor線程的多路複用器上,監聽讀操做,讀取客戶端發送的網絡消息
                                    sc.register(selector, SelectionKey.OP_READ);
                                }
                                if (key.isReadable()) {
                                    // 第九步:異步讀取客戶端請求消息到緩存區
                                    SocketChannel sc = (SocketChannel) key.channel();
                                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                                    int readBytes = sc.read(readBuffer);

                                    // 第十步:對ByteBuffer進行編解碼,若是有半包消息指針reset,繼續讀取後續的報文
                                    if (readBytes > 0) {
                                        readBuffer.flip();
                                        byte[] bytes = new byte[readBuffer.remaining()];
                                        readBuffer.get(bytes);
                                        String body = new String(bytes, "UTF-8");
                                        System.out.println("The time server receive order : " + body);
                                        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
                                                ? new java.util.Date(System.currentTimeMillis()).toString()
                                                : "BAD ORDER";
                                        //寫應答
                                        byte[] bytes2 = currentTime.getBytes();
                                        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes2.length);
                                        writeBuffer.put(bytes2);
                                        writeBuffer.flip();
                                        sc.write(writeBuffer);
                                    } else if (readBytes < 0) {
                                        // 對端鏈路關閉
                                        key.cancel();
                                        sc.close();
                                    } else
                                        ; // 讀到0字節,忽略
                                }
                            }
                        } catch (Exception e) {
                            if (key != null) {
                                key.cancel();
                                if (key.channel() != null)
                                    key.channel().close();
                            }
                        }
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        }
    }
}

注意:若是發送區TCP緩衝區滿,會致使寫半包,此時,須要註冊監聽寫操做位,循環寫,直到整包消息寫入TCP緩衝區框架

客戶端步驟:異步

 

客戶端:socket

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class TimeClientHandle implements Runnable {

    private String host;
    private int port;
private Selector selector; private SocketChannel socketChannel; private volatile boolean stop; public TimeClientHandle(String host, int port) { this.host = host == null ? "127.0.0.1" : host; this.port = port; try { //第一步:打開SocketChannel,用於建立客戶端鏈接 socketChannel = SocketChannel.open(); //第二步:設置SocketChannel爲非阻塞模式 socketChannel.configureBlocking(false); //第三步:建立多路複用器(在Reactor線程中) selector = Selector.open(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } @Override public void run() { try { // 第四步:socketChannel發起鏈接 if (socketChannel.connect(new InetSocketAddress(host, port))) { //第五步:若是直接鏈接成功,則註冊到多路複用器上 socketChannel.register(selector, SelectionKey.OP_READ); //第六步:發送請求消息,讀應答 byte[] req = "QUERY TIME ORDER".getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); socketChannel.write(writeBuffer); if (!writeBuffer.hasRemaining()) System.out.println("Send order 2 server succeed."); } else socketChannel.register(selector, SelectionKey.OP_CONNECT); } catch (IOException e) { e.printStackTrace(); System.exit(1); } while (!stop) { try { //第七步:多路複用器在run的無限循環體內輪詢準備就緒的Key selector.select(1000); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { if (key.isValid()) { //第八步:將鏈接成功的Channel註冊到多路複用器上 // 判斷是否鏈接成功 SocketChannel sc = (SocketChannel) key.channel(); if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(selector, SelectionKey.OP_READ); //發送請求消息,讀應答 byte[] req = "QUERY TIME ORDER".getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); sc.write(writeBuffer); if (!writeBuffer.hasRemaining()) System.out.println("Send order 2 server succeed."); } else System.exit(1);// 鏈接失敗,進程退出 } //監聽讀操做,讀取服務端寫回的網絡信息 if (key.isReadable()) { //第九步:讀取信息到緩衝區 ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); this.stop = true; } else if (readBytes < 0) { // 對端鏈路關閉 key.cancel(); sc.close(); } else ; // 讀到0字節,忽略 } } } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) key.channel().close(); } } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // 多路複用器關閉後,全部註冊在上面的Channel和Pipe等資源都會被自動去註冊並關閉,因此不須要重複釋放資源 if (selector != null) try { selector.close(); } catch (IOException e) { e.printStackTrace(); } } } package com.dxz.springsession.nio.demo6; public class TimeClient { /** * @param args */ public static void main(String[] args) { int port = 1234; if (args != null && args.length > 0) { try { port = Integer.valueOf(args[0]); } catch (NumberFormatException e) { // 採用默認值 } } new Thread(new TimeClientHandle("127.0.0.1", port), "TimeClient-001") .start(); } }

 

 抄錄地址:分佈式

  1. Java NIO系列教程(一) Java NIO 概述
  2. java nio詳解
  3. java NIO 運行原理介紹
相關文章
相關標籤/搜索