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/7642638https://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

 


免責聲明!

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



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