Java nioの初歩的な理解


Nioプログラミング
nioとはいったい何の略称ですか.new ioという人もいますが、これも公式の呼び方です.しかしbioは閉塞式ioであるためNon-block ioとも呼ばれる.何を呼んでもいいから、楽しければいい.
NIOの概要
コンセプト:
バッファBuffer
Bufferは、書き込みまたは読み出すデータを含むオブジェクトです.nioクラスライブラリにbufferオブジェクトを追加することは,新しいライブラリと元のI/Oの重要な違いを体現している.ストリーム向けI/Oでは、ストリームオブジェクトに直接データを書き込むか、ストリームオブジェクトに直接読み込むことができます.nioライブラリでは、すべてのデータがバッファで処理されます.バッファは実質的に配列であり、最もよく使われるのはByteBufferであるが、実際には各タイプが1つのBuffer(booleanを除く):ByteBuffer、CharBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBufferに対応している.
チャネルチャネルチャネル
チャネルは、ストリームとは異なり、ストリームは一方向であり、各ストリームはOutStreamまたはInputStreamのサブクラスでなければならないが、チャネルは、読み取り、書き込み、または両方で同時に行うことができる.チャネルはフルデュプレクスなので、オペレーティングシステムの最下位のAPIをよりよくマッピングできます.特にunixネットワークプログラミングモデルでは,下位オペレーティングシステムのチャネルはすべて全二重である.
マルチプレクサSelector
彼はnioの基礎です.マルチプレクサは、すでに準備されているタスクを選択する能力を提供します.簡単に言えば、Selectorは登録されているChannelを絶えずポーリングし、あるChannelに読み取りイベントや書き込みイベントが発生すると、このChannelは準備完了状態になり、Selectorにポーリングされ、SelectionKeyによってこの準備完了したChannelの集合を取得し、後続のIO操作を行うことができる.1つのSelectorは複数のChannelを同時にポーリングすることができ、JDKはselectの代わりにepoll()を使用して実現されるため、最大ハンドル1024/2048の制限はありません.これは、1つのスレッドがSelectorポーリングを担当し、何千ものクライアントにアクセスできることを意味します.これは確かに進歩です.
以上紹介した知識を1つのDemoで示します
TimeServer
package nio;

import java.io.IOException;

/** * Created by dubby on 16/3/13. */
public class TimeServer {
    public static void main(String[] args) throws IOException{
        int port = 8080;
        MultiplexerTimeServer multiplexerTimeServer = new MultiplexerTimeServer(port);
        new Thread(multiplexerTimeServer).start();
    }
}

MultiplexerTimeServer
package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/** * Created by dubby on 16/3/13. */
public class MultiplexerTimeServer implements Runnable {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop;


    /** *         ,       * @param port */
    public MultiplexerTimeServer(int port) {
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(port),1024);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("The time server is start in port : "+port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while(!stop) {
            try{
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while(it.hasNext()) {
                    key = it.next();
                    it.remove();
                    try{
                        handleInput(key);
                    } catch (Exception e){
                        if(key != null){
                            key.cancel();
                            if(key.channel() != null){
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(selector != null) {
            try{
                selector.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()){
            //          
            if(key.isAcceptable()){
                //     
                ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector,SelectionKey.OP_READ);
            }
            if(key.isReadable()){
                //    
                SocketChannel sc = (SocketChannel)key.channel();
                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("The time server receive order : "+body);
                    String currentTime = "QUERY".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"BAD ORDER";
                    doWrite(sc,currentTime);
                }else if(readBytes < 0){
                    //      
                    key.cancel();
                    sc.close();
                }else {
                    ;//  
                }
            }
        }
    }

    private void doWrite(SocketChannel sc, String response) throws IOException{
        if(response != null && response.trim().length()>0){
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            sc.write(writeBuffer);
        }
    }
}

以上がサービス側コードです.TimeClient
package nio;

/** * Created by dubby on 16/3/13. */
public class TimeClient {
    public static void main(String[] args) {
        int port = 8080;
        new Thread(new TimeClientHandler("127.0.0.1",port)).start();
    }
}

TimeClientHandler
package nio;

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;

/** * Created by dubby on 16/3/13. */
public class TimeClientHandler implements Runnable {

    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    public TimeClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try{
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try{
            doConnect();
        } catch (Exception e){
            e.printStackTrace();
        }
        int count = 0;
        while(!stop){
            try {
                selector.select(1000);
                Set<SelectionKey> selectKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectKeys.iterator();
                SelectionKey key = null;
                System.out.println(" : "+selectKeys.size());
                while(it.hasNext()){
                    key = it.next();
                    it.remove();
                    try{
                        handleInput(key);
                    } catch (Exception e){
                        key.cancel();
                        if(key.channel() != null){
                            key.channel().close();
                        }
                    }
                }
            } catch (IOException e) {
                System.exit(1);
            }
        }
        if(selector != null){
            try{
                selector.close();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private void doConnect() throws IOException{
        //      ,          ,    ,   
        if(socketChannel.connect(new InetSocketAddress(host,port))){
            System.out.println("    ");
            socketChannel.register(selector,SelectionKey.OP_READ);
            doWrite(socketChannel);
        } else{
            System.out.println("    ");
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    private void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()){
            //        
            SocketChannel sc = (SocketChannel)key.channel();
            if(key.isConnectable()){
                if(sc.finishConnect()){
                    sc.register(selector,SelectionKey.OP_READ);
                    doWrite(sc);
                } 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 {
                    ;
                }
            }
        }
    }

    private void doWrite(SocketChannel sc) throws IOException{
        byte[] req = "QUERY".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        sc.write(writeBuffer);
        if(!writeBuffer.hasRemaining()){
            System.out.println("Send order to server succeed.");
        }
    }
}

以上がクライアントコードです.
興味のある方はコードを見て、上で紹介したように、論理を理解するのは問題ではないはずです.