High-performance network communication technologies --java NIO

Background generated by a .NIO

BIO, input-output (original)
the NIO (Not-blocking IO) model nonblocking IO

          channel highway
(selector selector) client --------------------- -----> server-side multiplexing

main purpose: to improve the performance of the program, learn some advanced ideas BIO and NIO are synchronized IO two concepts must understand. 1) blocked (Block) and. non-blocking (noN-block) is a data-oriented in terms of      blocking: data is not ready, the program waits until the data is ready after just down the implementation of      non-blocking: Whether I have the data is not ready, the program down execution 2) synchronous and asynchronous relative to our IO event.      sync: when the IO processing program, the program can not do otherwise, we should wait to do something else after the event is finished IO      asynchronous: no IO concerned about the process, as long as when dealing with IO, you can do something else, then wait for IO event completes the notification three existing .java IO model BIO JDK1.4 previous IO model, blocking IO  NIO JDK1.4 after the new IO model, non-blocking IO, learn Linux multiplexing technique, a polling mechanism AIO








 







 

 
         IO model only after JDK1.7, true asynchronous processing, the IO read and write operations entirely to our operating system, Linux epoll learning mode

interpretation of the principle of four .java NIO
   
1). Multiplexer (Channel Channel) equivalent highway

2). polling mechanism (Seletor selector)

    client (client) (selector) butler boss (boss)
   guests with butler said, I'm looking for your boss to help, housekeeper told the guests that we are now busy boss that you first take a moment, the first cup of tea. (registration behavior), to give customers a grade (SelectionK), No. 001, over, and now the boss free, and can be dealt with, after processing, to be recycled grades, to the next person, the customer will be sent away. 

          After the incident must be done such as IO, customers can go (synchronous)

        3). SelectionKey time tag corresponds to

        4) .Buffer (data buffer)

        5) .NIO common API Channel: server: ServerSocketChannel BIO: ServerSocket Client: SocketChannel BIO: the Socket open (); // build roads, repair the highway up channel.regist (selector, registration identification) Selector Selector open (); // open for business selectedKeys (); // get the current already registered all grades information buffer PUT (); // buffer to write data inside get (); // read data flip (); // read-write mode is switched clear (); // Clear buffer SelectionKey grade isAccptable () // can accept client connections isConnctionable () // whether connection isReadable () // buffer is readable isWriteable () // if writable
   


























About five .java AIO asynchronous non-blocking IO

have not yet caught on, you can understand the server: AsynchronousServerSocketChannel Client: AsynchronousSocketChannel CompletionHandler: notification procedures, IO operation is successful, or failed   six write code and demo. BIO: blocking IO synchronization package com.yz.io.bio; Import java.io.IOException; Import java.io.InputStream; Import java.net.ServerSocket; Import java.net.Socket; / **  * the Created by the yz ON 2018/2/5.  * / public class {BioServer     the ServerSocket Server;     / **      * a server configured      * @param Port      * /     public BioServer (int Port) {         the try {             Server new new = the ServerSocket (Port);






























            System.out.println ( "Bio service is started, listening port is:" Port +);
        } the catch (IOException E) {
            e.printStackTrace ();
        }
    }

    / **
     * listen for client requests over
     * /
    public void listener () throws IOException {
        the while (to true) {
            the Socket = server.accept Client ();
            the InputStream client.getInputStream IS = ();
            byte [] = BUFF new new byte [1024]; // buffer
            int len = is.read (BUFF);
            IF (len> 0) {
                String MSG = new new String (BUFF, 0, len);
                System.out.println ( "receives the message sent by the client:" + MSG);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new BioServer(8080).listener();
    }
}


package com.yz.io.bio;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created by yz on 2018/2/5.
 */
public class BioClient {

    public static void main(String[] args) throws IOException {
        Socket client = new Socket("localhost",8080);
        /**
         * 获取一个输出流
         */
        OutputStream os = client.getOutputStream();
        os.write("报个到".getBytes());
        os.close();
        client.close();
    }
}

NIO: 非阻塞IO  selector+非阻塞 同步 常用框架: Mina2.0 Netty5.0 

package com.yz.io.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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by yz on 2018/2/5.
 */
public class NioServer {


    int port = 8080;
    Server a ServerSocketChannel;
    Selector Selector;
    // buffer
    the ByteBuffer receiveBuffer = ByteBuffer.allocate (1024);
    the ByteBuffer sendBuffer = ByteBuffer.allocate (1024);

    the Map <the SelectionKey, String> = new new sessionMsg the HashMap <> ();

    public NioServer (Port int ) throws IOException {
        / **
         * up to highway repair
         * /
        Server ServerSocketChannel.open = ();
        / **
         * Level also opened, can be multiplexed
         * /
        server.socket () the bind (the InetSocketAddress new new. (this.port));
        / **
         * the default is blocked, manually set to non-blocking, it is non-blocking
         * /
        server.configureBlocking (false);
        / **
         * Butler open for business
         * /
        Selector = Selector.open ();

        / **
         * Tell housekeeper, Boss is ready, and so there will be guests, to inform me
         * /
        server.register (Selector, SelectionKey. OP_ACCEPT);

        System.out.println ( "NiO service is started, listening port is:" + this.port);

    }

    public void listener () throws IOException {
        / **
         * polling
         * /
        the while (to true) {
            // a judgment, there is no currently registered customers, there is no queue, there is no take a number of
           int I = the selector.select ();
            IF (I == 0) Continue;
            the Set <the SelectionKey> Keys selector.selectedKeys = ();
            Iterator <the SelectionKey> = keys.iterator Iterator ();
            the while (iterator.hasNext ()) {
                // a handle to a
                process (iterator.next ());
                dismissed after processed //
                the Iterator.remove ();
            }
        }
    }


    / **
     * method for processing data
     * /
    Private void process (SelectionKey Key) throws IOException {
        // we must first determine the customer has no boss to establish a good connection with us
        IF (key.isAcceptable ()) {
            SocketChannel = client Server. Accept ();
            client.configureBlocking (to false);
            client.register (Selector, SelectionKey.OP_READ);
        IF the else} (key.isReadable ()) {
            receiveBuffer.clear ();
            if the data can be read // Analyzing
            the SocketChannel Client = (the SocketChannel) key.channel ();
            int len = client.read (receiveBuffer);
            IF (len > 0) {
                String MSG = new new String (receiveBuffer.array (), 0, len);

                sessionMsg.put (Key, MSG);
                System.out.println ( "Get message sent by the client:" + msg);
            }
            // after reading can tell the butler wrote
            client.register (Selector, SelectionKey.OP_WRITE);
        } the else iF (key.isWritable ()) {
            // determine whether the data can be written
            ! if (sessionMsg.containsKey (key) ) {
                return;
            }

            the SocketChannel Client = (the SocketChannel) key.channel ();
            sendBuffer.clear ();
            sendBuffer.put (new new String (sessionMsg.get (Key) + ", hello, Your request has been processed."). the getBytes ());
            sendBuffer.flip (); // read-write mode switching

            client.write (sendBuffer);
            client.register (Selector, SelectionKey.OP_READ);
        }
    }

    public static void main (String [] args) throws IOException {
        NioServer new new (8080) .listener ();
    }
}


Package com.yz.io.nio;

Import java.io.IOException;
Import a java.io.InputStream;
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.Scanner;
import java.util.Set;

/**
 * Created by yz on 2018/2/5.
 */
public class NioClient {

    SocketChannel client ;
    InetSocketAddress serverAddress = new InetSocketAddress("localhost",8080);
    Selector selector;

    //缓冲区
    ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
    ByteBuffer sendBuffer = ByteBuffer.allocate(1024);

    public NioClient() throws IOException {
        //先开路
        = the SocketChannel.open Client ();
        client.configureBlocking (to false);
        the client.connect (serverAddress);

        Selector = Selector.open ();

        client.register (Selector, SelectionKey.OP_CONNECT);

    }

    public void the session () throws IOException {
        // must first determine whether the connection has been established
        iF (client.isConnectionPending ()) {
            client.finishConnect ();
            System.out.println ( "in the console to register the name");
            // tell the housekeeper can write things
            client. Register (Selector, SelectionKey.OP_WRITE);
        }
        Scanner Scanner Scan new new = (the System.in);
        the while (scan.hasNext ()) {
            String name = scan.nextLine();
            if("".equals(name)){
                continue;
            }
            process(name);
        }
    }

    public void process(String name) throws IOException {
        boolean unFinish = true;
        while (unFinish){
            int i = selector.select();
            if(i == 0) continue;
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isWritable()){
                    sendBuffer.clear();
                    sendBuffer.put(name.getBytes());
                    sendBuffer.flip();

                    client.write(sendBuffer);
                    client.register(selector,SelectionKey.OP_READ);
                }else if(key.isReadable()){
                    receiveBuffer.clear();
                    int len = client.read(receiveBuffer);
                    if(len > 0){
                        receiveBuffer.flip();
                        System.out.println("获取到服务端反馈的消息:"+new String(receiveBuffer.array(),0,len));
                        client.register(selector,SelectionKey.OP_WRITE);
                        unFinish = false;
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new NioClient().session();
    }

}


AIO: 异步非阻塞IO

package com.yz.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;


/**
 YZ ON 2018/2/5 the Created by *.
 * /
Public class AioServer {

    AsynchronousServerSocketChannel Server;

    the ByteBuffer receviceBuff = ByteBuffer.allocate (1024);

    int Port = 8080;

    public AioServer (int Port) throws IOException {
        this.port = Port;
        // to the rich, first build roads
        Server AsynchronousServerSocketChannel.open = ();
        // open level
        server.bind (the InetSocketAddress new new ( "localhost", this.port));
    }

    public void listener () {
        new new the Thread () {
            RUN void public () {
                System.out.println ( "Aio service is started, listening port:" + port);
                server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

                    //成功后的回调
                    @Override
                    public void completed(AsynchronousSocketChannel client, Void attachment) {
                        server.accept(null,this);
                        process(client);
                    }

                    @Override
                    public void failed(Throwable exc, Void attachment) {
                        System.out.println("异步IO失败");
                    }
                    private void process(AsynchronousSocketChannel client){
                        try {
                            receviceBuff.clear();
                            int len = client.read(receviceBuff).get();
                            receviceBuff.flip();
                            System.out.println("已接到客户端发来的消息:"+new String(receviceBuff.array(),0,len));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                while (true){}
            }
        }.run();
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        new AioServer(8080).listener();
        Thread.sleep(20000);
    }

}

package com.yz.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.Scanner;
import java.util.concurrent.Future;

/**
 * Created by yz on 2018/2/5.
 */
public class AioClient {

    AsynchronousSocketChannel client;

    InetSocketAddress serverAddress = new InetSocketAddress("localhost",8080);

    ByteBuffer sendBuffer = ByteBuffer.allocate(1024);

    public AioClient() throws IOException {
        client = AsynchronousSocketChannel.open();
        Future<?> f = client.connect(serverAddress);
        System.out.println("客户端已启动");
    }

    public void send(String content){
        sendBuffer.clear();
        sendBuffer.put(content.getBytes());
        sendBuffer.flip();
        client.write(sendBuffer);
    }

    public static void main(String[] args) throws IOException {
        AioClient client = new AioClient();
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String content  = sc.nextLine();
            client.send(content);
        }
    }

}

Seven summary

BIO: blocking IO synchronization

NIO: Non-blocking IO synchronization selector + non-blocking common framework: Mina2.0 Netty5.0

AIO: asynchronous non-blocking IO



Published 43 original articles · won praise 32 · views 40000 +

Guess you like

Origin blog.csdn.net/yz2015/article/details/79444899