Netty Channel Interface noun comprehension

Source: Internet
Author: User
Tags getmessage map data structure

1.Channel
The channel is responsible for reading the data, writing the object, a bit similar to the stream inside the old IO. It differs from stream, the channel is bidirectional, can write can read, and stream to divide OutStream and InputStream. Moreover, in NiO, users should not read and write data directly from the channel, but should use buffer to read and write data to the channel via buffer.
A channel can be provided to the user below a few messages
(1) Current status of the channel, such as Open or closed
(2) A Channelconfig object that represents some of the channel's parameters, such as buffersize

(3) All I/O operations supported by the channel (e.g. Read,write,connect.bind) and Channelpipeline (explained below)

2.ChannelConfig
Channel parameters, which are stored in the map data structure

3.channelevent 
Channelevent A generalized view of the events related to the channel, whether it is divided upstream events and downstream events two chunks, which need attention here, If the server is the main body, the process from the client data to the server is upstream, while the server-to-client data transfer process is called downstream, and if the client is the principal, The process from server to client is upstream for the client, and the client-to-server process is downstream for the client.  
Upstream events include:  
messagereceived:---messageevent  when information is accepted;
Exceptioncaught:---exceptionevent  When an exception occurs,---channelstateevent  when
Channelopen:channel is turned on;
When the Channelclosed:channel is closed---channelstateevent 
Channelbound:channel is turned on and ready to connect but not connected--- channelstateevent 
Channelunbound:channel is opened not ready to connect when---channelstateevent 
When the Channelconnected:channel is connected---channelstateevent 
Channeldisconnected:channel When the connection is broken--- channelstateevent 
When the interestops of Channelinterestchanged:channel is changed------channelstateevent 
Writecomplete: Write to--writecompletionevent  when the remote end is complete;

Downstream events includes:
Write: When sending messages to the channel--messageevent
Bind: Binds a channel to the specified local address--channelstateevent
Unbind: Unbind the current local port--channelstateevent
Connect: Connecting the Channel to a remote machine--channelstateevent
Disconnect: Disconnect the channel from the remote machine--channelstateevent
Close: Turn off channel--channelstateevent

Note that there is no open event, because when a channel is created by ChannelFactory, the channel is always opened.

There are also two event types where a child channel exists when the parent channel is present
Childchannelopen: Sub channel is opened---channelstateevent
Childchannelclosed: Child channel is closed---channelstateevent

4.ChannelHandler
Channel is the carrier responsible for transmitting the data, then the data must be processed according to the requirements, then this time to use the Channelhandler
Different processes can be used to build different channelhandler and then put into channelpipeline
It is also necessary to have channelevent trigger to reach Channelhandler, so there are two sub interfaces below according to the event Channelupstreamhandler
and Channeldownstreamhandler.
A channelhandler usually needs to store some state information as a judgment message, and a common practice defines a variable
Like what

public class Dataserverhandler extends {@link Simplechannelhandler} {
*
* <b>private Boolean loggedin;</b>
*
* {@code @Override}
* public void messagereceived ({@link Channelhandlercontext} ctx, {@link messageevent} e) {
* {@link Channel} ch = E.getchannel ();
* Object o = e.getmessage ();
* IF (o instanceof loginmessage) {
* Authenticate ((loginmessage) o);
* <b>loggedin = true;</b>
*} else (o instanceof getdatamessage) {
* if (<b>loggedIn</b>) {
* Ch.write (Fetchsecret ((getdatamessage) o));
*} else {
* FAIL ();
* }
* }
* }
* ...
* }

Create a new handler instance per channel.
*//See {@link bootstrap#setpipelinefactory (channelpipelinefactory)}.
* Public class Dataserverpipelinefactory implements {@link Channelpipelinefactory} {
* Public {@link channelpipeline} getpipeline () {
* Return {@link channels}.pipeline (<b>new dataserverhandler () </b>);
* }
* }


In addition to this, each channelhandler can get or set data from the Channelhandlercontext, so the following is the way to use Channelhandlercontext
Setting variables

* {@code @Sharable}
* Public class Dataserverhandler extends {@link Simplechannelhandler} {
*
* {@code @Override}
* public void messagereceived ({@link Channelhandlercontext} ctx, {@link messageevent} e) {
* {@link Channel} ch = E.getchannel ();
* Object o = e.getmessage ();
* IF (o instanceof loginmessage) {
* Authenticate ((loginmessage) o);
* <b>ctx.setattachment (TRUE) </b>;
*} else (o instanceof getdatamessage) {
* IF (<b>boolean.true.equals (Ctx.getattachment ()) </b>) {
* Ch.write (Fetchsecret ((getdatamessage) o));
*} else {
* FAIL ();
* }
* }
* }
* ...
* }

* Public class Dataserverpipelinefactory implements {@link Channelpipelinefactory} {
*
* Private static final Dataserverhandler <b>SHARED</b> = new Dataserverhandler ();
*
* Public {@link channelpipeline} getpipeline () {
* Return {@link channels}.pipeline (<b>SHARED</b>);
* }
* }
There is a difference between the two approaches,above the variable procedure, each new handler object, the variable is not shared, while the following channelhandlercontext are shared

If you need to share data between different handler, then what to do, then use channellocal
Example:
Public final class Dataserverstate {
*
* <b>public static final {@link channellocal}&lt; Boolean&gt; LoggedIn = new {@link channellocal}&lt; Boolean&gt; () {
* Protected Boolean InitialValue (channel channel) {
* return false;
* }
*}</b>
* ...
* }
*
* {@code @Sharable}
* Public class Dataserverhandler extends {@link Simplechannelhandler} {
*
* {@code @Override}
* public void messagereceived ({@link Channelhandlercontext} ctx, {@link messageevent} e) {
* Channel ch = e.getchannel ();
* Object o = e.getmessage ();
* IF (o instanceof loginmessage) {
* Authenticate ((loginmessage) o);
* <b>dataserverstate.loggedin.set (CH, true);</b>
*} else (o instanceof getdatamessage) {
* IF (<b>dataserverstate.loggedin.get (CH) </b>) {
* Ctx.getchannel (). Write (Fetchsecret ((getdatamessage) o));
*} else {
* FAIL ();
* }
* }
* }
* ...
* }
*
*//Print The remote addresses of the authenticated clients:
* {@link Channelgroup} allclientchannels = ...;
* for ({@link Channel} ch:allclientchannels) {
* IF (<b>dataserverstate.loggedin.get (CH) </b>) {
* SYSTEM.OUT.PRINTLN (Ch.getremoteaddress ());
* }
* }
* </pre>

5.ChannelPipeline
Channelpipeline is a collection of Channelhandler, which is implemented by referring to the intercepting filter pattern in the Java EE, allowing the user to fully grasp if an event is handled in a handler. At the same time allow multiple handler inside the pipeline to interact with each other.

Intercepting filter:http://java.sun.com/blueprints/corej2eepatterns/patterns/interceptingfilter.html For each channel need to have a corresponding channelpipeline, when the channel set Channelpipeline can no longer for channel reset Channelpipeline. Also the recommended practice is to build channelpipeline instead of building channelpipeline by channels this helper class

Often pipeline add multiple handler, which are based on business logic

Like below.
{@link Channelpipeline} p = {@link channels}.pipeline ();
* P.addlast ("1", New Upstreamhandlera ());
* P.addlast ("2", New Upstreamhandlerb ());
* P.addlast ("3", New Downstreamhandlera ());
* P.addlast ("4", New Downstreamhandlerb ());
* P.addlast ("5", New Simplechannelhandler ());
Upstream event execution handler in order should be 125
Downstream event execution handler in order should be 543
Simplechannelhandler is a class that implements both Channelupstreamhandler and Channeldownstreamhandler.
It just has logic, and if the data needs to be encoded in a format, it needs to be written
* {@link Channelpipeline} pipeline = {@link channels#pipeline () Channels.pipeline ()};
* Pipeline.addlast ("decoder", New Myprotocoldecoder ());
* Pipeline.addlast ("encoder", New Myprotocolencoder ());
* Pipeline.addlast ("executor", new {@link Executionhandler} (New {@link Orderedmemoryawarethreadpoolexecutor} (16, 1048576, 1048576)));
* Pipeline.addlast ("handler", New Mybusinesslogichandler ());
which
Protocol Decoder-Convert binary to Java object
Protocol Encoder-Converting Java objects to binary
Executionhandler-applies a thread model.
Business logic handler-performs The actual business logic (e.g. database access)
Although Channelpipeline cannot be reset for the channel, the Channelpipeline itself is thread-safe, so you can add delete Channelhandler at any time for Channelpipeline

Note that the following code cannot be written to the desired effect  
* public class Firsthandler extends {@link Simplechannelupstreamhandler} { 

* {@code @Override} 
* public void messagereceived ({@link Channelhandlercontext} ctx, {@link Messageevent} e) { 
*/Remove This handler from the pipeline, 
* Ctx.getpipeline (). Remove (This); 
*//And let SecondHandler handle the current event. 
* Ctx.getpipeline (). AddLast ("2nd", New SecondHandler ()) ;  
* Ctx.sendupstream (e);  
*}&NBSP;
*}&NBSP;
Premises now pipeline only the last firsthandler, 
It is obvious that you want to remove the Firsthandler from the pipeline and then add the SecondHandler. And pipeline need to have a handler, so if you want to reach this effect, then you can  
Add SecondHandler First and then remove Firsthandler.  

6.ChannelFactory
The channel's factory class, which is the class used to generate the channel, ChannelFactory generates the corresponding channel according to the specified communication and network, such as
The channel generated by Nioserversocketchannelfactory is based on the NIO server socket.
When a channel is created, Channelpipeline is attached as a parameter to the channel.
Two-step operation is required for ChannelFactory shutdown
First, close all the factory produced by the channel including the Sub channel. Channelgroup#close () is usually called.
Second, release the ChannelFactory resource, call Releaseexternalresources ()

7.ChannelGroup
A set of channel groups that contains one or more open channel,closed the channel is automatically removed from the group, and a channel can be in one or more channelgroup
If you want to broadcast a message to multiple channel, you can use group to implement
Like what:
{@link Channelgroup} recipients = new {@link Defaultchannelgroup} ()
Recipients.add (Channela);
Recipients.add (CHANNELB);
Recipients.write (Channelbuffers.copiedbuffer ("Service would shut down for maintenance in 5 minutes.", Charsetutil.utf_8) );

When Serverchannel and non-Serverchannel are both in Channelgroup, any IO request operation is performed in the Serverchannel first and then in the other channel.
This rule is very useful for shutting down a server.

8.ChannelFuture
In Netty, all IO transmissions are asynchronous, all of which require a data + state to determine if all the transmissions are successful, and this is channelfuture.


9.ChannelGroupFuture
For the result of a channelgroup asynchronous operation, he, like Channelfuture, includes data and status. The difference is that he consists of all the channelfuture of the channel inside the Channelgroup.

10.ChannelGroupFutureListener
For channelgroupfuture listeners, it is also recommended to use Channelgroupfuturelistener instead of await ();

11.ChannelFutureListener
Channelfuture Listener, monitoring the results of channelfuture.

12.ChannelFutureProgressListener
Monitor the channelfuture process, such as the transfer of a large file. and Channelfuturelistener only listens channelfuture complete unfinished

13.ChannelHandlerContext
How to get handler and his pipeline and other handler in pipeline to Exchange, then use Channelhandlercontext, Channelhandler can pass the event to the nearest handler through Channelhandlercontext's Sendxxxstream (channelevent), Can get pipeline through Channelhandlercontext Getpipeline, and modify him, Channelhandlercontext can also store state information attments.
A Channelhandler instance can have one or more channelhandlercontext

14.ChannelPipelineFactory
Factory class for producing Channelpipe

15.ChannelState
Record channel State constants

Netty Channel Interface noun comprehension

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.