Learn Java Netty (iii)--Channel

Source: Internet
Author: User
Tags comparable throwable

Learn Java Netty (iii) –channel

Introduction: Netty package of channel, look at the definition of the official website
A nexus to a network socket or a component which is capable of I/O operations such as read, write, connect, and bind.
Networking sockets or components that can be I/O operations (such as read, write, connect, and BIND)

A channel provides a user:
All I/O operations is asynchronous
Netty all operations in the channel are asynchronous and the request returns immediately, but does not guarantee that the request is complete

Channels is hierarchical
Channel is layered, a channel can have a parent, depending on how it was created, such as a socketchannel (client socket) is connected by Serversocketchannel (service end socket), So Serversocketchannel is similar to Socketchannel's parent

Downcast to access transport-specific operations
Transition down to access a specific transport protocol, that is, a subtype can also access the action of the parent type

Release Resources
Release the resource, the channel inside is also the socket file handle, we want close ()

The channel is an abstracted interface of Netty, and the channel in the Channel,netty in NiO encapsulates the operations associated with network IO and network IO. Very many functions

Source:
//channel is an interface class that inherits from AttributeMap and Comparable,attributemap is a map,comparable interface that stores properties forcing the overall ordering of objects that implement each of its classes Public  Interface channel extends attributemap, comparable<Channel > {    //Return unique identityChannelid ID ();//Returns the registered event loopEventLoop EventLoop ();//Return to parent channelChannel parent ();//Return channel (socket) configurationChannelconfig config ();//Decide whether to open, register, active    BooleanIsOpen ();BooleanIsregistered ();//source data, can obtain the underlying TCP parameter settings, etc.Channelmetadata metadata ();//Local address and remote addressSocketAddress localaddress (); SocketAddress remoteaddress ();//Close channel, return channelfuture means is asynchronous, does not block immediate return, in the future we can get the state of execution operationChannelfuture closefuture ();//data is readable    BooleanIsWritable ();Long Bytesbeforewritable ();    unsafe unsafe ();    Channelpipeline pipeline ();    Bytebufallocator Alloc ();    Channelpromise newpromise ();    Channelprogressivepromise newprogressivepromise ();    Channelfuture newsucceededfuture ();    Channelfuture newfailedfuture (throwable cause);    Channelpromise voidpromise ();    Channelfuture bind (socketaddress localaddress);    Channelfuture Connect (socketaddress remoteaddress);    Channelfuture Connect (socketaddress remoteaddress, socketaddress localaddress);    Channelfuture disconnect ();    Channelfuture Close ();    Channelfuture deregister ();    Channelfuture bind (socketaddress localaddress, Channelpromise Promise);    Channelfuture Connect (socketaddress remoteaddress, Channelpromise Promise);    Channelfuture Connect (socketaddress remoteaddress, socketaddress localaddress, Channelpromise Promise);    Channelfuture Disconnect (Channelpromise promise);    Channelfuture Close (channelpromise promise); Channelfuture deregister (channelpromise PromiSE);    Channel read ();    Channelfuture Write (Object msg);    Channelfuture Write (Object msg, channelpromise Promise);    Channel Flush ();    Channelfuture Writeandflush (Object msg, channelpromise Promise);    Channelfuture Writeandflush (Object msg); Interface Unsafe

From the interface class can see the channel operation is very much, the latter method I did not write comments, can see are some operations, return to Channelfuture or channelpromise, select some of the following points to explain.

Channel

Encapsulated a lot of protocol TCP,UDP, communication model Nio,oio,aio, etc., from the above can be seen on these operations provide a whole package interface is the channel, the necessary time can be transformed.
The interface provides:
Channel status, IsOpen (), iswritable ()
Configuration parameters of Channel, config ()
Channel supported operation, BIND (), read (), connect ()

channelfuture

All channel operations are asynchronous, and some operations of the channel return channelfuture do not block, but return immediately, and at some point in the future we will be able to obtain a state to determine whether the state of the operation is completed or canceled.
Note that the Channelfuture object is immediately returned when the operation is executed. The method provided in Channelfuture is to allow the check operation to complete.

channelpromise

Inheritance Relationship:
Future <-channelfuture <-channelpromise
Channelpromise inherited the Channelfuture,channelfuture method is mainly to determine the future state of operation, and Channelpromise in addition to inherit Channelfuture method, but also to achieve the setting of the future state of writing method ,
It's written on the source.
Special {@link channelfuture} which is writable.
Special writable Channelfuture
such as Channelfuture return error, when we use channelpromise, we can change the return result, wake up other operations, a bit of the sense of the condition variable in the thread.

Channelpipeline

Speaking of Channelpipeline first to say the responsibility chain design mode, the simple point is that some can handle the request of the object string together to form a chain, the object being processed do not know who to deal with, so in this processing chain on the last search, who deal with who will accept this object for processing.
Examples of real life, such as the superior assigned a task to do a software (handled object), looking to have a row of siege Lions (processing request objects), so this task passed between them, each siege lion judge whether they can do, can do to accept the request.

Pipeline is this chain of responsibility, we can register, add, delete processing event object, and then when the object to be processed on this pipeline, which processing event object can be processed to receive it.

Responsibility Chain design Pattern

part of the code:
publicvoidinitChannelthrows Exception {    ch.pipeline().addLast(new StringDecoder());    //分隔符解码器    DelimiterBasedFrameDecoder    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));    ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));}

The above adds 3 processing event objects, string decoding, delimiter decoding, and log information. When the corresponding events are generated, they are accepted and processed
Note: Each channel will automatically create a Channelpipeline instance when instantiated. Channelpipeline is thread-safe and can be deleted at any time.

Channelhandler

Channelhandler is channelpipeline above the registered processing event object, each Channelhandler interface implementation class to complete a certain function, and can be flexibly added in the pipeline pipeline, Channelhandler is also known as an event interceptor, which is intercepted when it encounters events that can be handled.
Channelhandler Support Annotations
@Sharable is a common channelhandler for multiple pipeline
@skip are skipping this Channelhandler

Channelhandleradapter

The Channelhandleradapter provides the user with a Channelhandler adapter, We can customize the class to inherit Channelhandleradapter and then re-implement the Channelhandler method based on how we need to handle the event object.

Example:
 Public  class serverhandler extends channelhandleradapter {Serverhandler () {System.out.println ("Serverhandler was created"); }//Override this method     Public void Channelread(Channelhandlercontext ctx, Object msg)throwsexception{ctx.write (msg); System.out.println ("Send msg"); Bytebuf buf = (bytebuf) msg;byte[] req =New byte[Buf.readablebytes ()];        Buf.readbytes (req); String BODY =NewString (req,"UTF-8"); System.out.println ("Server Received:"+ body); Ctx.write (RESP); } Public void Channelreadcomplete(Channelhandlercontext CTX)throwsexception{write the write data into the buffer, wait until the complete state and then flush the bufferCtx.flush (); } Public void Exceptioncaught(Channelhandlercontext ctx, throwable cause) {//Error printing error and close CTXLogger.log (Level.warning,"unexcepted exception from downstream", cause);    Ctx.close (); }}

The classes and interfaces that are closely related to this channel and channel are almost simply introduced, and we generally know their principles and their usage, and it is much easier to see and use other extended classes that inherit them.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learn Java Netty (iii)--Channel

Related Article

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.