Netty Composition (i)

Source: Internet
Author: User
Tags event listener throwable
Channel

Channel is the basic structure of NIO. It represents an open connection that is used to connect to an entity such as a hardware device, a file, a network socket, or a program component, capable of performing one or more different I/O operations, such as read or write.

Now think of Channel as a means of transport that can be "turned on" or "closed", "connected" or "disconnected", and used as an incoming and outgoing data. Callback (callback)

Callback (callback) is an easy way to provide another method as a reference so that the latter can invoke the former at a suitable time. This technique is widely used in various programming situations, one of the most common methods of informing others that the operation is complete.

Netty internal use callback to handle events. Once such a callback is triggered, the event can be handled by the implementation of the interface Channelhandler. As in the following code, once a new connection is established, call Channelactive () and print a message.

Listing 1.2 Channelhandler triggered by a callback

The public class Connecthandler extends Channelinboundhandleradapter {@Override the public
    void Channelactive ( Channelhandlercontext ctx) throws Exception {   //1
        System.out.println (
                "Client" + ctx.channel (). Remoteaddress () + "Connected");
    }

1. Call Channelactive () when a new connection is established Future

Future provides another way to notify that an application operation has been completed. This object acts as a placeholder for the result of an asynchronous operation, and it will complete and provide results at some point in the future.

The JDK comes with interface java.util.concurrent.Future, but the provided implementation only allows you to manually check whether the operation is complete or blocked. This is cumbersome, so Netty provides its own implementation, channelfuture, for use when performing asynchronous operations.

Channelfuture provides multiple attachment methods to allow one or more channelfuturelistener instances. This callback method, Operationcomplete (), is invoked when the operation completes. The event listener is able to confirm whether the operation was successful or wrong. If it is the latter, we can retrieve the resulting throwable. In short, the notification mechanism provided by Channelfuturelistener does not require a manual check to see if the operation is complete.

Each Netty outbound I/O operation returns a channelfuture, which is not blocked. This is what Netty calls "bottom-up asynchronous and event-driven."

The following example simply demonstrates the return of a channelfuture as part of I/O operations. When the call to connect () will be directly non-blocking, and the call is done behind the scenes. Because threads are non-blocking, there is no need to wait for the operation to complete, but to do something else, so this makes resource utilization more efficient.

Listing 1.3 Callback in action

Channel Channel = ...;
Will not block
channelfuture future = Channel.connect (
    new Inetsocketaddress ("192.168.0.1", 25));

1. Connect to remote address asynchronously

The following code describes how to use Channelfuturelistener. First, connect to the remote address. Next, call Connect () via channelfuture to register a new channelfuturelistener. When the listener is notified that the connection is complete, we check the status. If it is successful, write the data to Channel, otherwise we retrieve the Throwable in the channelfuture.

Note that the handling of the error depends on your project. Of course, specific mistakes need to be constrained. For example, if a connection fails, you can try to connect to another.

Listing 1.4 Callback in action

Channel Channel = ...;
Will not block
channelfuture future = Channel.connect (            //1
        new Inetsocketaddress ("192.168.0.1"));
Future.addlistener (New Channelfuturelistener () {  //2
@Override public
void Operationcomplete ( Channelfuture future) {
    if (future.issuccess ()) {                    //3
        bytebuf buffer = Unpooled.copiedbuffer (
                " Hello ", Charset.defaultcharset ()); 4
        channelfuture wf = Future.channel (). Writeandflush (buffer);                5
        //...
    } else {
        throwable cause = Future.cause ();        6
        cause.printstacktrace ();}}
);

1. Connect asynchronously to a remote peer node. The call returns immediately and provides channelfuture.

2. Notify the registration of a channelfuturelistener after the operation is completed.

3. Check the status of the operation when Operationcomplete () is called.

4. If successful, create a bytebuf to save the data.

5. Send data asynchronously to remote. Return to Channelfuture again.

6. If there is an error, throw throwable to describe the cause of the error. Event and Handler

Netty uses different events to inform us of the state of the change or the state of the operation. This allows us to trigger the appropriate behavior based on the events that occur.

These behaviors may include: Log data conversion flow control application logic

Since Netty is a network framework, events are clearly related to inbound or outbound data flow. Because some events may trigger incoming data or changes in state including: Read user event error for active or inactive connection data

Outbound events are caused by an action that will be triggered in the future. These include: Turn on or off a connection to a remote write or scour data to the socket

Each event can be assigned to a user's method of implementing a handler class. This demonstrates that an event-driven paradigm can be directly converted to an application building block.

Figure 1.3 shows an event that can be handled by a series of event handlers

Figure 1.3 Event Flow

The Channelhandler of Netty is the basic abstraction of various processing programs. Imagine that each processor instance is a callback that is used to perform a response to various events.

On top of that, Netty also provides a rich set of predefined handlers that you can use to open the box. For example, codecs for various protocols include HTTP and SSL/TLS. Internally, Channelhandler uses events and future itself to create consumers with Netty attribute abstractions.

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.