Read it together. Netty in Action (a)

Source: Internet
Author: User

The Netty is an asynchronous event-driven network application framework that enables rapid development of maintainable, high-performance, protocol-oriented servers and clients. In network programming, blocking, non-blocking, synchronization, and Asynchrony are often referred to. What is the difference between synchronous (synchronous) IO and asynchronous (asynchronous) Io, what is blocking (blocking) IO and non-blocking (non-blocking) IO respectively?

There are several common I/O models:

Let's take a scene to illustrate what the above means:

I went shopping with my baby at the weekend, I was hungry at noon, we were ready to eat. Weekend people, eat need to queue, my baby and I have the following options:

(1) Blocking: I and the baby after the meal, do not know when to do a good job, had to sit in the restaurant and so on, until the good, and then eat out before leaving. The baby would like to go shopping with me, but do not know when the meal can be done, but with me in the restaurant, and so on, and can not go shopping, until after eating dinner before going shopping, in the middle of waiting for the cooking time wasted. This is typical of blocking.

(2) Non-blocking: The baby is not willing to wait in vain in this, and want to go shopping malls, and worry about the rice good. So we stroll for a while, come back to ask the waiter meal good no, to go back and forth several times, the meal has not eaten is almost exhausted. This is non-blocking. It needs constant polling and is ready.

(3) Multiplexing: Similar to the second scheme, the restaurant installed an electronic screen to display the status of the order, so that I and the baby shopping for a while, come back without having to ask the waiter, directly to see the electronic screen on it. So that everyone's meal is good, all directly look at the electronic screen can be, this is the typical IO multiplexing, such as SELECT, poll, Epoll.

(4) Async: The baby does not want to go shopping, and the restaurant is too noisy, want to have a good rest. So we order takeout, make a phone call, and then I and the baby can have a good rest at home (here to ignore the details of the home with the baby), the food delivery staff to send to the home. This is the typical asynchronous, just need to make a phone call, and then can do their own things, the meal is ready to send.

so the difference between blocking non-blocking is that it is simple to understand that you need to do one thing immediately to get a return response, if you can't get an immediate answer, you need to wait, then it blocks, otherwise it can be understood as non-blocking.

In fact, the difference between synchronous and asynchronous: is the thread in the process of waiting to be able to do something else , if it is synchronous, the threads have been waiting or to poll the results, if it is asynchronous, the thread returned directly to do other work, and the completion of this I/O will be actively notify the thread to complete. in fact, synchronization and Asynchrony are for application-to-kernel interactions. During synchronization, the process triggers an IO operation and waits or polls to see if the IO operation is complete. After the process triggers the IO operation in the asynchronous process, it returns directly, does its own thing, IO gives the kernel to handle, and completes after the kernel notifies the process IO.

In fact, we often use Ajax is asynchronous JavaScript and XML technology, in jquery we can configure the Async:false property set Ajax for synchronous request, in fact, when the JS processing Ajax, will open a separate AJAX worker to process the request, and then the main thread will do something else and he will come back to process the request result when the main thread receives the callback notification for that request.

The following two images show the blocking I/O and the non-blocking I/O model provided by Java NIO in Java Network programming:

Using blocking I/O to handle multiple connections using selector non-blocking I/O

The use of the selector model has the following benefits:

(1) Fewer threads handle many connections, reducing the overhead associated with memory management and context switching.

(2) Threads can also be used for other tasks when no I/O is required to process.

After introducing these concepts, let's look at some of the core components of Netty.

1.channel

The channel is a basic construct of Java NIO and represents a development connection to the entity, such as read operations and write operations. channel channels and streams are very similar, mainly with the following differences:

    • The channel can be read or written, and the stream is generally one-way (read or write only).
    • The channel can read and write asynchronously.
    • Channels are always read and written based on buffer buffers.

In Java, the channel is implemented as follows:

    • FileChannel
    • Datagramchannel
    • Socketchannel
    • Serversocketchannel

FileChannel is used to read and write data for files. Datagramchannel data read and write for UDP. Socketchannel is used to read and write data for TCP. Serversocketchannel allows us to listen for TCP link requests, and each request will be created with a socketchannel. So serversocketchannel does not transmit data.

2. Callbacks

A callback is actually a method. Callbacks are used inside Netty to handle events, and when a callback is triggered, the associated event can be handled by the Channelhandler implementation.

3.Future

The future provides another way to notify the application when the operation is complete, providing access to the results of this asynchronous operation. The future of the Java concurrent Package allows only manual checks to see if the corresponding operation has been completed, or has been blocked until it is complete, so Netty provides its implementation-channelfuture is used to invoke when executing asynchronous. Channelfuture also provides additional methods for these methods to enable us to register one or more Channelfuturelistener instances, the callback methods of these listeners: Operationcomplete (), The outbound I/O operation that will be called for each netty when the corresponding operation completes will return a channelfuture, in which the Connect () method is returned directly and is not blocked.

1 Channel channel = ...; 2 channelfuture future = Channel.connect (new// asynchronous connection to remote node

The following example shows the use of Channelfuture and callbacks:

1Channel Channel = ...;2Channelfuture future = Channel.connect (NewInetsocketaddress ("192.168.9.1", 25));//connect asynchronously to a remote node3Future.addlistener (NewChannelfuturelistener () {//register a Channelfuturelistener to get notified when the operation is complete4 @Override5       Public voidOperationcomplete (channelfuture future) {6               if(Future.issuccess ()) {//If the operation is successful, perform the appropriate action7                 //...8 9}Else{TenThrowable cause = Future.cause ();//exception handling for failed operations One cause.printstacktrace (); A          } -      } -});

can actually put Channelfuturelistener is considered a more granular version of the callback. Callbacks and Channelfuturelistener complement each other, constituting one of the most critical components of Netty.

4. Events and Channelhandler

Netty use different events to notify us of changes in state or state of operations, events that may be triggered by inbound data or related state changes include:

(1) Connection activation or connection deactivation

(2) Data read

(3) User events

(4) Error events

The outbound event is the result of an action that will be triggered in the future, including:

(1) Open or close the connection to the remote node.

(2) Write or flush the data to the socket.

Each event can be distributed to a user-implemented method in the Channelhandler class, showing how the Channelhandler chain handles inbound events (the same is true for outbound events):

Netty's Channelhandler provides a basic abstraction for processors, and Netty also provides a number of predefined Channelhandler implementations that can be used out of the box, including those for various protocols (such as HTTP or SSL/TLS). Channelhandler, Inside, Channelhandler himself also used the events and the future.

5. Summary

Netty abstracts the selector from the application by triggering events, eliminating all distribution codes that would otherwise have to be manually written, and internally, each channel will be assigned a eventloop to handle all events, including:

(1) Registration of events of interest

(2) Sending events to Channelhandler

(3) Arranging for further action

The eventloop itself is driven by only one thread, which handles all I/O events for a channel and does not change throughout the lifetime of the channel, which eliminates the need to synchronize in your channelhandler.

In the next section we will delve into the basics of Netty's API and programming model.

Read it together. Netty in Action (a)

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.