Java Network Programming (iv)----asynchronous non-blocking AIO and Proactor model __ Programming

Source: Internet
Author: User
Tags class definition epoll throwable

(AIO) NIO 2.0 introduces the concept of a new asynchronous channel and provides an implementation of asynchronous file channels and asynchronous socket channels. True asynchronous non-blocking I/O when asynchronous socket channels correspond to event-driven I/O (AIO) in UNIX network programming. He does not need too much selector to poll the registered channel for asynchronous reading and writing, thus simplifying the programming model of NIO.

Jdk7 previous NIO is non-blocking io, operating system low-level, such as Linux, is implemented with IO multiplexing Select or Epoll, nor asynchronous IO. Asynchronous IO is currently limited to file systems on Linux and has not been widely used, and many platforms do not have it.
Java AIO is implemented using IOCP on Windows, which is true asynchronous IO. On Linux, it is through epoll to simulate asynchrony. AIO Use

AIO offers four types of asynchronous channels and different I/O operations:
Asynchronoussocketchannel:connect,read,write
Asynchronousfilechannel:lock,read,write
Asynchronousserversocketchannel:accept
Asynchronousdatagramchannel:read,write,send,receive

Of course, we will focus on the use of network IO (TCP), first focus on Asynchronoussocketchannel, first of all, a simple view of the type of API.

Asynchronoussocketchannel class definition

Public abstract class Asynchronoussocketchannel implements Asynchronousbytechannel, Networkchannel

Creates an asynchronous network channel and binds to a default group.

public static Asynchronoussocketchannel open () throws IOException

We can then invoke various methods of Asynchronoussocketchannel to perform asynchronous operations, which require passing in a Completionhandler interface parameter as the callback interface.

1. Connect the asynchronous network channel to the remote server, and use the specified Completionhandler to await completion of the notification.

public abstract <A> Void Connect (socketaddress remote,  A attachment, completionhandler<void,? Super A> Handler

2. Read data from the asynchronous network channel to the specified buffer and use the specified Completionhandler to await completion of the notification.

Public final <A> void Read (Bytebuffer DST, A attachment,  Completionhandler<integer,? Super A> handler)

3. Write the data in the buffer to the asynchronous network channel and use the specified Completionhandler to await the completion of the notification.

Public final <A> void write (Bytebuffer src, A attachment, Completionhandler<integer,? Super A> handler)

Completionhandler interface, as the processing interface after asynchronous execution, callback the completed (V result, A attachment) method when it is completed correctly, and perform a failure callback void failed (Throwable exc, a Attachment) method.

Public interface Completionhandler<v,a> {

    //invoked. Operation has completed.
    void completed (V result, A attachment);
    Invoked when a operation fails.
    void failed (Throwable exc, A attachment);
}

It's easy to use, call the asynchronous method, and then pass the implemented callback interface as a parameter to the program itself to perform the callback.
AIO also has another way of using future, because Hi is blocked and this is not the way to tell. Proactor

The Proactor pattern includes the following roles: Handle: Handle, connection to identify the socket or read-write operation, asynchronous Operation Processor: Asynchronous Operation processor, responsible for asynchronous operation, generally implemented by the operating system kernel; Asynchronous Operation: Asynchronous Operation completion Event queue: Completion of events queues, completion of asynchronous operations placed in queues waiting for subsequent use proactor: an active device, providing an event loop for an application process The result of an asynchronous operation is taken from the completion event queue, and the corresponding subsequent processing logic is called; Completion Handler: completes the event interface; It is generally an interface composed of callback functions; concrete completion Handler: Complete the specific logic implementation of event processing, implement callback interface, define specific application processing logic.


Execution Process: Application startup, invoking asynchronous operation interface functions provided by the async operation Handler, running independently of the application and asynchronous operations after the invocation; the application can invoke new asynchronous operations, while others can do so concurrently; The application initiates the Proactor, and performs an infinite loop of events, Wait for the completion of the event to arrive; The asynchronous operation processor performs an asynchronous operation and puts the result into the completion event queue when completed;
The actuator extracts the result from the completion event queue and distributes it to the corresponding completion event callback function processing logic;

The only handle and completion Handler that we can touch in Java AIO programs are called when used
Asynchronoussocketchannel:connect,read,write and
The Asynchronousserversocketchannel:accept method acts as a handle handle, then the program will help us to implement the asynchronous operation according to the above process, and finally distribute the execution results to the corresponding completion in Proactor. In handler, callback the completed or failed function that we implement.

In Proactor mode, an event handler (or a generation initiated by the event distributor) directly initiates an asynchronous read and write operation (equivalent to a request), and the actual work is done by the operating system. The parameters to be provided include a buffer for reading data, the size of the data read, or a buffer for storing outgoing data, and the callback function after the request. The event dispatcher learns about the request, silently waits for the request to complete, and forwards the completion event to the appropriate event handler or callback. For example, event handlers on Windows post an asynchronous IO operation (called overlapped technology), and an IO complete event such as event dispatcher completes. The typical implementation of this asynchronous pattern is based on the underlying asynchronous API of the operating system, so we can call it "system level" or "really" asynchronous, because the specific reads and writes are performed by the operating system. AIO Code Implementation

Because the amount of code is too much, here only the server-side code, the client's code in the following link to the AIO section, my code is also based on the following code changes, many comments for easy to understand.
Source: http://blog.csdn.net/anxpp/article/details/51512200

public class Server {
    private static int default_port = 12345;
    private static Asyncserverhandler Serverhandle;
    Public volatile static long Clientcount;
    public static void Start () {
        start (default_port);
    }
    public static synchronized void start (int port) {
        if (null!= serverhandle) return
            ;
        Serverhandle = new Asyncserverhandler (port);
        /Open Server Threads
        new Thread (serverhandle, "Server"). Start ();
    public static void Main (string[] args) {
        server.start ();
    }
}
Server thread implementation, creating ServerSocket and executing its accept method asynchronously
public class Asyncserverhandler implements Runnable {public countdownlatch latch;
    Public Asynchronousserversocketchannel channel; public Asyncserverhandler (int port) {try {//Create service-side channel channel = Asynchronousserversocketch
            Annel.open ();
            Binding Port Channel.bind (new Inetsocketaddress (port));
        SYSTEM.OUT.PRINTLN ("Server started, port number:" + port);
        catch (IOException e) {e.printstacktrace ();
        @Override public void Run () {//countdownlatch initialization latch = new Countdownlatch (1); The connection used to receive clients//This code can only be used once, receive a request from a client//to implement multiple request processing can see the implementation of Accepthandler () parameters channel.accept (this,new Acc
        Epthandler ());
        System.out.println ("Main thread continues execution");
        try {//Let the scene block here, to prevent the service side from executing after the completion of Exit latch.await ();
        catch (Interruptedexception e) {e.printstacktrace (); }
    }
}

2. After the server receives the connection, the callback implements the Completionhandler Accepthandler class.

As a handler receive client connection
to the public class Accepthandler implements Completionhandler<asynchronoussocketchannel, asyncserverhandler> {
    @Override public
    Void completed (Asynchronoussocketchannel channel, Asyncserverhandler serverhandler) {
        //continue to accept requests from other clients
        server.clientcount++;
        System.out.println ("Number of connected clients:" + server.clientcount);

        。。。。 This line is the key to continue to accept other requests asynchronously/
        /To perform an asynchronous connection request after each connection is received, so that multiple connections can be processed
        serverHandler.channel.accept (Serverhandler, this );

        Create a new buffer
        bytebuffer buffer = bytebuffer.allocate (1024);
        Read asynchronously, and the third parameter is the business handler
        channel.read (buffer, buffer, new Readhandler (channel)) that receives the message callback;
    @Override public
    void failed (Throwable exc, Asyncserverhandler serverhandler) {
        exc.printstacktrace ();
        ServerHandler.latch.countDown ();
    }

3. The above Accepthandler invokes the read operation asynchronously, and the Readhandler completed () method is invoked after the read operation succeeds. The corresponding callback interface for write operations is implemented as an internal class.

public class Readhandler implements Completionhandler<integer, bytebuffer> {//For reading half packet messages and sending replies private ASYNCHR
    Onoussocketchannel Channel;
    Public Readhandler (Asynchronoussocketchannel channel) {this.channel = channel;
        //Read to message processing @Override public void completed (Integer result, bytebuffer attachment) {//flip operation
        Attachment.flip ();
        According to byte[] message = new byte[attachment.remaining ()];
        Attachment.get (message);
            try {string expression = new String (message, "UTF-8");
            SYSTEM.OUT.PRINTLN ("Server received message:" + expression);

            String Calrresult = "Message from server at this time";
        Send a message to the client dowrite (Calrresult);
        catch (Unsupportedencodingexception e) {e.printstacktrace ();
        }///Send message private void Dowrite (String result) {byte[] bytes = Result.getbytes ();
     Bytebuffer WriteBuffer = bytebuffer.allocate (bytes.length);   Writebuffer.put (bytes);
        Writebuffer.flip (); The asynchronous write data parameter is the same as the previous read//The callback interface is implemented as an internal class Channel.write (WriteBuffer, Writebuffer,new Completionhandler<integ
                Er, bytebuffer> () {@Override public void completed (Integer result, Bytebuffer buffer) {  If it is not sent, continue sending until the IF (buffer.hasremaining ()) Channel.write is completed (buffer, buffer,
                this);
                    else{//Create a new buffer Bytebuffer Readbuffer = bytebuffer.allocate (1024); 
                Asynchronous read the third parameter is the business handler Channel.read (Readbuffer, Readbuffer, New Readhandler (channel)) for receiving message callbacks; @Override public void failed (Throwable exc, bytebuffer attachment
                ) {try {channel.close ();
    catch (IOException e) {}}}); @Override Public VOID failed (Throwable exc, bytebuffer attachment) {try {this.channel.close ();
        catch (IOException e) {e.printstacktrace (); }
    }
}
comparison of reactor and Proactor

Https://segmentfault.com/a/1190000002715832#articleHeader7

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.