Java IO系列之四:NIO通信模型


分布式rpc框架有很多,比如dubbo,netty,還有很多其他的產品。但他們大部分都是基於nio的,

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

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

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

3.線程之前通過wait,notify通信,減少線程切換。

 

NIO使用步驟

服務端步驟:

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緩沖區

客戶端步驟:

 

客戶端:

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 運行原理介紹

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM