Mina, Netty, Twisted learn Together (ix): Asynchronous IO and callback functions

Source: Internet
Author: User

With JavaScript or jquery, you know that JavaScript, especially jquery, has a lot of callback functions, such as Ajax, jquery animations, and so on.

$.get (URL, function () {doSomething1 ();//(3)}); (1) doSomething2 ();  (2)
The above code is jquery Ajax, because Ajax is asynchronous, so in the process of requesting a URL does not block the program, that is, the program runs to (1) does not wait for the results of the AJAX request, continue to run down (2). The second parameter of $.get is a callback function when the AJAX request is complete. This callback function is called to run (3).

This example is only used to understand the concept of asynchronous, did not play JS can not understand the classmate also does not matter.

In traditional io (bio/blocked io), all IO operations block the current thread until the operation is complete, and all steps are step-by-step. Like what:

OutputStream output = Socket.getoutputstream (); out.write (data); Return Out.flush () after the IO operation is complete; SYSTEM.OUT.PRINTLN ("message sent");
However, in asynchronous network programming, the IO operation is asynchronous, that is, an IO operation is not blocked to wait for the result of the operation. The program will continue to run down.


In Mina, Netty, and twisted, very many network IO operations are asynchronous, and there is one end of write data in the direction network, the connect operation of the client connection server, and so on.


For example, the Write method of Netty (and the Writeandflush method) does not indicate that the data has been sent after the write statement is run. Instead of just sending this data, the program does not block until it is sent, but continues to run down. So suppose there are some operations that you want to run after the write is complete, such as closing the connection after write is complete. Here are some of the things that are problematic, and it's possible to close the connection before the data write goes out:

Channel ch = ...; Ch.writeandflush (message); Ch.close ();
Then the problem comes. Excavator... Since the above is not the correct wording. So how do I do some other things after I have finished IO operation?

When the asynchronous IO operation is complete, either success or failure. will notify the program again. As for how to deal with the notification of the completion of the delivery, in Mina, Netty, twisted. There will be a similar callback function implementation method.

Netty:

In Netty, the write and Writeandflush methods have a return value, and the type is channelfuture.

The Channelfuture AddListener method can be added to the Channelfuturelistener listener. The abstract method of the Channelfuturelistener interface Operationcomplete will be called when write finishes (whether successful or unsuccessful), and we only need to implement this method to handle some of the finished write operations. For example, close the connection when write is complete.

@Overridepublic void Channelread (Final channelhandlercontext ctx, Object msg) throws Unsupportedencodingexception {// Read operation omitted ...//Send data to clientchannelfuture future = Ctx.writeandflush ("message"); callback function called after the return value type Channelfuturefuture.addlistener (New Channelfuturelistener () {//write operation is complete @overridepublic void Operationcomplete (channelfuture future) throws Exception {if (future.issuccess ()) {//Succeeded System.out.println (" Write operation succeeded ");} else {System.out.println ("write operation failed");} Ctx.close (); Suppose you need to close the connection after write, and close should be written in Operationcomplete.

Note The return value of the Close method is also channelfuture}});}

In the above code, the close operation is done in Operationcomplete, which guarantees that the close connection will not be completed until the write is complete.

Note that the close closed connection is the same as asynchronous, and its return value is also channelfuture.

MINA:

Mina and Netty are similar. The Session.write return value is the Writefuture type.

Writefuture is also able to join the Iofuturelistener listener through the AddListener method. The abstract method of the Iofuturelistener interface Operationcomplete is called when write finishes, regardless of success or failure.

Suppose you need to do something after the write is complete. Just implement the Operationcomplete method.

@Overridepublic void Messagereceived (iosession session, Object message) throws Exception {//read operation omitted ...// Send data to Clientwritefuture future = Session.write ("message"); Future.addlistener (New Iofuturelistener<writefuture > () {///The callback function called after the write operation @overridepublic void Operationcomplete (writefuture future) {if (Future.iswritten ()) { System.out.println ("write operation succeeded");} else {System.out.println ("write operation failed");}});}
The difference between Mina and Netty is the Close method of closing the connection. The close () method with no parameters is deprecated. Instead, use the Close (Boolean immediately) method with a Boolean-type parameter.

Immediately is true to close the connection directly, or false to wait for all asynchronous write to complete before closing the connection.

So the following is the correct wording:

Session.write ("message"); Session.close (false); Although write is asynchronous, the immediately parameter is false to wait for the write to close before closing the connection
Twisted:

In Twisted, twisted.internet.defer.Deferred is similar to the future in Mina, Netty, and can be used to add a callback function after the completion of asynchronous IO.

However, twisted does not return deffered in the Write method. Although the Write method is also asynchronous. The following is the use of twisted to implement a simple tcpclient to learn how deffered.

#-*-coding:utf-8–*-from twisted.internet import reactorfrom twisted.internet.protocol import Protocolfrom twisted.int Ernet.endpoints import Tcp4clientendpoint, Connectprotocolclass ClientProtocol (Protocol):    def sendMessage (self) :        self.transport.write ("Message") # Write is also asynchronous        self.transport.loseConnection () # Loseconnection will wait for the write to close before closing the connection # Connection server successful callback function def connectsuccess (p):    print "Connectsuccess"    P.sendmessage () # Connection Server failed callback function def connectfail (failure):    print "connectfail" point = Tcp4clientendpoint (reactor , "localhost", 8080) d = connectprotocol (point, ClientProtocol ()) # Asynchronously connects to server, returns Defferedd.addcallback (connectsuccess # Set the callback function after successful connection d.adderrback (Connectfail) # Set the callback function after the connection failed Reactor.run ()
In twisted, the Loseconnection method that closes the connection waits for the asynchronous write to complete before closing, similar to Session.close (false) in Mina. Twisted you want to close the connection directly can use Abortconnection, similar to Mina in Session.close (true).



Fork Brother reproduced please indicate the source: http://blog.csdn.net/xiao__gui/article/details/40016907



Mina, Netty, Twisted learn Together (ix): Asynchronous IO and callback functions

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.