Traditional socket bio to pseudo asynchronous IO to NiO introduction to the final AIO

Source: Internet
Author: User
Tags readline

Keywords: NIO, Io,bio,aio and evolution reasons

I do not really understand NIO, this article is only a brief introduction of the code under the https://github.com/zhaikaishun/NettyTutorial socket01 Traditional bio communication: Synchronous blocking mode

Look at the picture, invade and delete

The traditional model is the Bio mode, which is synchronized blocking, just look at the example below.
Server Side

        ServerSocket server = null; Bio, use a ServerSocket class for socket transfer
        int prot = 9999;
        try {
            Server = new ServerSocket (prot);
            SYSTEM.OUT.PRINTLN ("Server start ...");
            Block while
            (true) {
                socket socket = server.accept ();//!! Until the client establishes the socket connection, will walk the following operation
                System.out.println ("Client establishes Scoket connection only then goes Here");
                Create a new thread to execute the client's task
                new Thread (new Serverhandler (socket)). Start ();

        The following do not have to see the
        catch (Exception e)
....

Serverhandler Processing class , mainly used for output, stay here for 5000 milliseconds

in = new BufferedReader (New InputStreamReader (This.socket.getInputStream ()));
out = new PrintWriter (This.socket.getOutputStream (), true);
String BODY = null;
while (The BODY = In.readline ())!=null) {
    System.out.println ("Server:" + body);
    Thread.Sleep (5000);
    Respond to the client
    out.println ("This is the server-side loopback response data.");
}

Client Side

String address = "127.0.0.1";
int PORT = 9999;

Socket = new Socket (address, PORT);
in = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
out = new PrintWriter (Socket.getoutputstream (), true);

Send data out.println to server side
("received request data from client ...");
System.out.println ("After the execution of this sentence, the following in.readline is blocked");
In.readline () is blocked and must wait for the server to complete before reading to
String response = In.readline ();
System.out.println ("Client:" + response);

To analyze the mode of NIO, run the Server,server output first

Run Client,client output again

After the execution of this sentence, the following in.readline is blocked  

Server-Side output

Client establishes Scoket connection before going here
Server: Receive request data from client ...

Run client output after 5 seconds:

Client: This is the server-side echo response data.

Summary: server-side socket socket = server.accept (); Will cause blocking until the client establishes the connection before performing the following action
Client-side: String response = In.readline (); can also cause blocking until the server.accept response occurs
Also, each client creates a thread on the server side, and if the client is more concurrent, the server will not be able to withstand the paralysis of the pseudo-asynchronous IO pattern

See picture: Invasion and deletion

A pattern prior to the implementation of NIO
Look directly at the example, and the above is good, but the server end uses a thread pool, the client's socket encapsulated into a task task, so that when more client concurrency, it will be executed by waiting, will not let the thread suddenly up too much, Here's just a log of the server-side code, and the other code is consistent with the above example
Server Side

int PORT = 9999;
ServerSocket server = null;
BufferedReader in = null;
PrintWriter out = null;
try {
    Server = new ServerSocket (PORT);
    SYSTEM.OUT.PRINTLN ("server Start");
    Socket socket = NULL; 
    Handlerexecutorpool Executorpool = new Handlerexecutorpool (m, 1000);  In fact, the whole is the same, but here is added a thread pool just while
    (true) {
        socket = server.accept ();
        Executorpool.execute (new Serverhandler (socket));
    }

catch (Exception e) 

thread pool Encapsulation class Handlerexecutorpool

public class Handlerexecutorpool {

    private executorservice executor;
    Public Handlerexecutorpool (int maxpoolsize, int queuesize) {
        this.executor = new Threadpoolexecutor (
                Runtime.getruntime (). Availableprocessors (),
                maxpoolsize, 
                120L, 
                timeunit.seconds,
                new Arrayblockingqueue<runnable> (queuesize));

    public void execute (Runnable task) {
        This.executor.execute (Task);
    }
}
the relationship and difference between NiO and IO:

Blocking concept: When the application gets the network data, if the network transmission is slow, then the program waits until the transmission is complete.
Non-blocking: Applications can get ready data directly without waiting

NIO: Synchronous non-blocking

Synchronization: Applications are directly involved in IO read and write, and programs are blocked directly to a method
Asynchronous: All Io is given to the operating system, and when the operating system completes the IO operation, it will notify our application

Synchronous asynchronous is about how the server service side is executed
Blocking is talking about technology, the way the data is received, the State (Io,nio) NIO

Several major concepts
Buffer
Channel
Selecter is a socket.
Buffer

Use the Flip method reset, the location is back to 0, but the back of the empty will clear 0 (better), do not recommend the use of Posistion methods to deal with
The specific buffer operation case, here also does not want to remember (NiO really directly uses very few), the code is under the Kaishun.nio.test.TestBuffer class AIO

Asynchronous non-blocking: I don't see it here, I don't know for the moment, TODO Zhaikaishun 2017-06-10[have time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.