1. 程式人生 > >Java中NIO及基礎實現

Java中NIO及基礎實現

NIO:同步非阻塞IO

來源:BIO是同步阻塞IO操作,當執行緒在處理任務時,另一方會阻塞著等待該執行緒的執行完畢,為了提高效率,,JDK1.4後,引入NIO來提升資料的通訊效能

NIO中採用Reactor設計模式,註冊的匯集點為Selector,NIO有三個主要組成部分:Channel(通道)、Buffer(緩衝區)、Selector(選擇器)

 

Reactor設計模式:Reactor模式是一種被動事件處理模式,即當某個特定事件發生時觸發事件,可參考,https://blog.csdn.net/feimataxue/article/details/7642638,https://www.cnblogs.com/bitkevin/p/5724410.html

NIO採用了輪詢的方式來觀察事件是否執行完畢,如:A讓B列印某個檔案,BIO會一直等待著B返回,期間自己不做其他事情,而NIO則會不斷的詢問B是否完成,未完成則處理自己的時,直至B完成

 

Channel(通道):Channel是一個物件,可以通過它讀取和寫入資料

 

Selector(物件選擇器): Selector是一個物件,它可以註冊到很多個Channel上,監聽各個Channel上發生的事件,並且能夠根據事件情況決定Channel讀寫

 

程式碼實現:(此實現參考網路上可用的例子)

NIO客戶端實現:

package com.learn.nio.client;

import com.study.info.HostInfo;
import com.study.util.InputUtil;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOEchoClient {

    public static void main(String[] args) throws Exception{
        SocketChannel clientChannel = SocketChannel.open();
        clientChannel.connect(new InetSocketAddress(HostInfo.HOST_NAME,HostInfo.PORT));
        ByteBuffer buffer = ByteBuffer.allocate(50);
        boolean flag = true;
        while (flag){
            buffer.clear();
            String input = InputUtil.getString("請輸入待發送的資訊:").trim();
            buffer.put(input.getBytes());   //將資料存入緩衝區
            buffer.flip();  //  重置緩衝區
            clientChannel.write(buffer);    //傳送資料
            buffer.clear();
            int read = clientChannel.read(buffer);
            buffer.flip();
            System.err.print(new String(buffer.array(), 0, read));
            if("byebye".equalsIgnoreCase(input)){
                flag = false;
            }
        }
        clientChannel.close();
    }
}

 

NIO服務端實現:

package com.learn.nio.server;

import com.study.info.HostInfo;

import java.net.InetSocketAddress;
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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NIOEchoServer {

    private static class EchoClientHandle implements Runnable {

        //客戶端
        private SocketChannel clientChannel;
        // 迴圈結束標記
        private boolean flag = true;
        public EchoClientHandle(SocketChannel clientChannel){
            this.clientChannel = clientChannel;
        }

        @Override
        public void run() {
            ByteBuffer byteBuffer = ByteBuffer.allocate(50);
            try {
                while (this.flag){
                    byteBuffer.clear();
                    int read = this.clientChannel.read(byteBuffer);
                    String msg = new String(byteBuffer.array(), 0, read).trim();
                    String outMsg = "【Echo】" + msg + "\n"; // 迴應資訊
                    if("byebve".equals(msg)){
                        outMsg = "會話結束,下次再見!";
                        this.flag = false;
                    }
                    byteBuffer.clear();
                    byteBuffer.put(outMsg.getBytes());  //回傳資訊放入緩衝區
                    byteBuffer.flip();
                    this.clientChannel.write(byteBuffer);// 回傳資訊
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception{
        // 為了效能問題及響應時間,設定固定大小的執行緒池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // NIO基於Channel控制,所以有Selector管理所有的Channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 設定為非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 設定監聽埠
        serverSocketChannel.bind(new InetSocketAddress(HostInfo.PORT));
        // 設定Selector管理所有Channel
        Selector selector = Selector.open();
        // 註冊並設定連線時處理
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服務啟動成功,監聽埠為:" + HostInfo.PORT);
        // NIO使用輪詢,當有請求連線時,則啟動一個執行緒
        int keySelect = 0;
        while ((keySelect = selector.select()) > 0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey next = iterator.next();
                if(next.isAcceptable()){    //  如果是連線的
                    SocketChannel accept = serverSocketChannel.accept();
                    if(accept != null){
                        executorService.submit(new EchoClientHandle(accept));
                    }
                    iterator.remove();
                }
            }
        }
        executorService.shutdown();
        serverSocketChannel.close();
    }
}

工具類:

package com.study.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputUtil {
    private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in));

    private InputUtil(){
    }

    public static String getString(String prompt){
        boolean flag = true;    //資料接受標記
        String str = null;
        while (flag){
            System.out.println(prompt);
            try {
                str = KEYBOARD_INPUT.readLine();    // 讀取一行資料
                if(str == null || "".equals(str)){
                    System.out.println("資料輸入錯誤,不允許為空!");
                }else {
                    flag = false;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }
}
package com.study.info;

public calss HostInfo {
    public static final String HOST_NAME = "localhost";
    public static final int PORT = 9999;
}

 

 

NIO結構參考文章: https://www.cnblogs.com/sxkgeek/p/9488703.html#_label2

&n