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 code above 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 execute (2). The second parameter of $.get is a callback function, which is invoked when the AJAX request is completed (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/blocking IO), all IO operations block the current thread until the operation is complete, and all steps are made step-by-step. For example:

OutputStream output = Socket.getoutputstream (); out.write (data); Returns Out.flush () after the IO operation is complete; SYSTEM.OUT.PRINTLN ("message sent to completion");
However, in asynchronous network programming, because the IO operation is asynchronous, that is, an IO operation will not block to wait for the result of the operation, the program will continue to execute downward.

In Mina, Netty, and twisted, many network IO operations are asynchronous, such as write to the other end of the network, connect to the client connection server, and so on.

For example, the Write method of Netty (and the Writeandflush method), after executing the write statement does not mean that the data has been sent out, but only to start sending this data, the program does not block waiting for the completion of the send, but continue to execute down. So if there's something that you want to do after write finishes, such as closing the connection after write completes, there's a problem with the following notation, which might 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 written correctly, how do I do some other things after the IO operation?

When the asynchronous IO operation is complete, the program is notified no matter whether it succeeds or fails. As for how to deal with notification of the completion of the send, in Mina, Netty, twisted, there will be similar to the implementation of the callback function.

Netty:

In Netty, the write and Writeandflush methods have a return value, and the type is channelfuture. The Channelfuture AddListener method can add Channelfuturelistener listeners. The abstract method of the Channelfuturelistener interface Operationcomplete will be called when write finishes (whether successful or unsuccessful), we only need to implement this method to handle some write-completed operations, For example, when write is complete, close the connection.

@Overridepublic void Channelread (Final channelhandlercontext ctx, Object msg) throws Unsupportedencodingexception {// Read operation omitted ...//Send data to client channelfuture future = Ctx.writeandflush ("message"); The return value type is Channelfuturefuture.addlistener (the new Channelfuturelistener () {///write operation is completed after the callback function called @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 (); If you need to close the connection after write, 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 done before write completes. Note that the close closed connection is also asynchronous, and its return value is also channelfuture.

MINA:

Similar to Mina and Netty, the Session.write return value is the Writefuture type. Writefuture can also add Iofuturelistener listeners through the AddListener method. The abstract method of the Iofuturelistener interface Operationcomplete is called when write completes, regardless of success or failure. If you need to do something after write completes, just implement the Operationcomplete method.

@Overridepublic void Messagereceived (iosession session, Object message) throws Exception {//read operation omitted ...// Send data to client writefuture future = Session.write ("message"); Future.addlistener (new iofuturelistener<writefuture> () The callback function called after the {//write operation completes @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 and uses the close (Boolean immediately) method with a Boolean 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 of false waits for the write to complete 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 callback functions after asynchronous IO is complete. However, twisted does not return deffered in the Write method, although the Write method is also asynchronous. The following is a simple TCP client using twisted to learn the use of 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 write to close before closing the connection # callback function for the successful connection to the Server 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 the 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 Session.close (true) in Mina.



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.