Netty Series II (transmission).

Source: Internet
Author: User
Tags configuration settings epoll

First, preface

In the previous article we mentioned that the core components of Netty are channel, callback, Future, Channelhandler, EventLoop, this article is mainly on the channel (Netty incoming and outgoing data carrier) to do some detailed explanation, as well as the introduction of the next Netty the built-in transport type.

Second, the core of the transmission

At the heart of the transport API is the interface Channel, which is used for all I/O operations. Hierarchy of Channel classes:

, each channel is assigned a channelpipeline and Channelconfig,channelconfig contains all configuration settings for the channel and supports hot updates. Channelpipeline is a container for channelhandler chains that holds all inbound and outbound data as well as Channelhandler instances.

Because the channel is unique, in order to ensure that the channel is declared as a sub-interface of Java.lang.Compareable, each channel has a different hash code, otherwise the error will be reported.

The Netty channel implementation is thread-safe, so you can store a reference to a channel and use it whenever you need to write data to a remote node, even when many threads are using it.

The other methods of Channel are as follows:

Tips:

1, the typical use of Channelhandler:

--Convert data from one format to another format.
--Provides notification of exceptions.
-Provide notification that the channel becomes active or inactive.
--provides notification when the channel is registered to EventLoop or is logged off from EventLoop.
--Provides notifications about user-defined events.

2. The wide range of functions provided by Netty only relies on a small number of interfaces. This means that you can make significant changes to your application logic without having to refactor your codebase on a large scale.

Iii. Netty Built-in transport type

The Netty includes some out-of-the-box transmissions. Because not all of their transports support each protocol, you must choose a transport that is compatible with the protocols that your application uses.

Name

Package

Describe

Application Scenarios

nio

using the Java.nio.channels package as the basis-selector-based approach

non-blocking I/O uses

epoll

Epoll () and non-blocking IO driven by JNI. This transport supports only a variety of features available on Linux, such as So_reuseport, faster than NIO transmissions, and is completely non-blocking

linux use

oio

using the java.net package as the basis-using the blocking stream

blocking I/O using

local

Local transport

Both the client and the server use the same JVM communication

Embedded

io.netty.channel.embedded

Embedded transmission, allowing the use of channelhandler without the need for a true network-based transmission. This is useful when testing your Channelhandler implementation

Implementation of Test Channelhandler

1, nio-non-blocking I/O

Java NIO provides a fully asynchronous implementation of all I/O operations. Where the selector behind is actually acting as a registry that shows the process:

User-level APIs that are common to all Netty transport implementations completely hide the implementation details of Java NIO, as shown in the previous demo, using Java NiO in Netty:

2. epoll-local non-blocking transmission for Linux

Netty provides a set of NiO APIs for Linux, which uses epoll in a more consistent way than its own design, and uses interrupts in a more lightweight way. If your application is designed to run on a Linux system, consider taking advantage of this version of the transfer, and you will find that it performs better than the JDK's NIO implementation under high load.

Netty support for Epoll in the code is also very simple, just make the following changes:

3. oio-old blocking I/O

How can netty be used and used to asynchronously transmit the same API to support OIO?

As mentioned above, in NiO, a eventloop corresponds to a thread, a Channel binds to a eventloop, and a eventloop can bind multiple channel to achieve asynchrony, that is, one thread can handle multiple channel. In Oio, a eventloop binds only one channel, which means that each thread handles only one channel, which is a bit like traditional IO, where the server (ServerSocket) writes a multithreading to handle concurrent requests from the client.

Now there is a problem, the channel is bidirectional, both can read, can also write. And stream is one-way, Oio use InputStream to read, OutputStream to write. So how does the channel achieve blocking read and write? The answer is that Netty uses the SO_TIMEOUT socket flag, which specifies the maximum number of milliseconds to wait for an I/O operation to complete, the channel is blocked during the I/O operation, and if the operation is not completed within the specified time interval, A sockettimeout Exception will be thrown. Netty will catch the exception and continue processing the loop. The next time EventLoop is run, it will try again. This is actually the only way that an asynchronous framework like Netty can support Oio.

Netty supports OIO in code, and is similar to NIO:

Tips:

I read the data from the hard drive, and then the program waits until the data is read and continues. This approach is the simplest, called blocking IO.
I read the data from the hard drive, and then the program continues to execute, and when the data is read, notify the current program (called Interrupts to the hardware, called Callbacks to the program), and then the program can process the data immediately, and can perform the current operation to read the data. Called non-blocking IO.

4. local--for Local transmission of internal JVM communication

Netty provides a local transport for asynchronous communication between a client and a server program running in the same JVM.

In this transmission, the socketaddress associated with the server Channel is not bound to the physical network address, and instead, as long as the server is still running, it is stored in the registry and logged off when the channel is closed. Because this transmission does not accept true network traffic, it does not interoperate with other transport implementations. Therefore, the client must also use it when it wants to connect to the server side (in the same JVM) that uses the transport.

Service-Side code:

     Public voidServer ()throwsinterruptedexception {FinalEchoserverhandler Serverhandler =NewEchoserverhandler (); Eventloopgroup Group=NewDefaulteventloop (); Try{Serverbootstrap bootstrap=NewServerbootstrap (); Bootstrap.group (Group, Group). Channel (Localserverchannel.class). Childhandler (NewChannelinitializer<localchannel>() {@Overrideprotected voidinitchannel (Localchannel ch) {Channelpipeline Pipeline=Ch.pipeline ();                        Pipeline.addlast (Serverhandler);            }                    }); Channelfuture channelfuture= Bootstrap.bind (NewLocalAddress ("foo") . sync (); System.out.println (echoserver.class. GetName () + "--started and listening for connections on--" +Channelfuture.channel (). localaddress ());        Channelfuture.channel (). Closefuture (). sync (); } finally{group.shutdowngracefully (). sync (); }    }
View Code

Client code:

     Public voidClient ()throwsinterruptedexception {eventloopgroup Group=NewNioeventloopgroup (); Try{Bootstrap Bootstrap=NewBootstrap (); Bootstrap.group (Group). Channel (Localchannel.class). Handler (NewChannelinitializer<localchannel>() {@Overrideprotected voidInitchannel (Localchannel ch)throwsException {ch.pipeline (). AddLast (NewEchoclienthandler ());            }                    }); Channelfuture channelfuture= Bootstrap.connect (NewLocalAddress ("foo") . sync ();        Channelfuture.channel (). Closefuture (). sync (); } finally{group.shutdowngracefully (). sync (); }    }
View Code

Note: now the client and server connection has been reported an exception, looked up a lot of information, but also see the many demos on Github, still no solution. Is there a great God to help me answer?

5, Embedded

Netty provides an additional transport that allows you to embed a set of Channelhandler as helper classes inside other Channelhandler. In this way, you will be able to extend the functionality of a channelhandler without having to modify its internal code.

The key to Embedded transmission is a specific channel implementation known as Embeddedchannel.

If you want to write unit tests for your own Channelhandler implementation, consider using Embedded transport.

reference:"Netty in ACTION"

Demo Source code: Https://github.com/JMCuixy/NettyDemo

Netty Series II (transmission).

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.