Netty Getting Started Tutorial

Source: Internet
Author: User
Tags getmessage sin jboss

What is Netty?

Nature: A jar package from JBoss

Objective: To rapidly develop high-performance, high-reliability network server and client programs

Pros: Provides asynchronous, event-driven network application frameworks and tools

Popular saying: A so-so deal with the socket

What if there's no netty?

Ancient: Java.net + java.io

Modern times: Java.nio

Others: Mina,grizzly

Why not Mina?

1, are Trustin Lee's works, Netty later;

2, Mina will be the kernel and some features of the link too tightly, so that users do not need these features can not be detached, compared to the performance will be reduced, netty solve the design problem;

3, Netty document clearer, a lot of Mina features in Netty;

4, Netty update cycle is shorter, the release of the new version is relatively fast;

5, their architecture is not very different, Mina by Apache Survival, and Netty by JBoss, and JBoss very high degree of integration, Netty has the support of Google Protocal buf, there is more complete IOC container support (Spring,guice, JBOSSMC and OSGi);

6, Netty more simple to use than Mina, Netty you can customize the processing upstream events or/and downstream events, you can use decoder and encoder to decode and encode the content sent;

7, Netty and Mina in the processing of UDP, there are some differences, netty the UDP non-connected features exposed, and Mina to the advanced level of UDP abstraction, UDP can be used as a "connection-oriented" protocol, and to Netty to do this is more difficult.

Characteristics of Netty

Design

Unified API for different protocols (blocking and non-blocking)

Flexible and scalable event-driven model

Highly customizable threading model

Reliable, no-connection data socket support (UDP)

Performance

Better throughput, low latency

More resource-saving

Minimize unnecessary memory copies

Safety

Complete SSL/TLS and STARTTLS support

Ability to operate well in applets and Android-restricted environments

Robustness

No longer outofmemoryerror due to too fast, too slow, or over-load connections

There is no longer an inconsistency between the read and write frequency of NiO in high-speed network environment

Use

Complete Javadoc, user guides and examples

Simplicity and simplicity

Trust only in JDK1.5

Look at the example!

Server side:

Java code
Package me.hello.netty;  Import Org.jboss.netty.bootstrap.ServerBootstrap;  Import org.jboss.netty.channel.*;  Import Org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;  Import Org.jboss.netty.handler.codec.string.StringDecoder;    Import Org.jboss.netty.handler.codec.string.StringEncoder;  Import java.net.InetSocketAddress;    Import java.util.concurrent.Executors;  /** * God Bless you!          * Author:fangniude * date:2013-07-15 * * * public class Nettyserver {public static void main (string[] args) { Serverbootstrap bootstrap = new Serverbootstrap (New Nioserversocketchannelfactory (Executors.newcachedthreadpool (), E            Xecutors.newcachedthreadpool ()));          Set up the default event pipeline. Bootstrap.setpipelinefactory (New Channelpipelinefactory () {@Override public channelpipeline get Pipeline () throws Exception {return channels.pipeline (new Stringdecoder (), New Stringencoder (), New Serv Erhandler ());            }          });          Bind and start to accept incoming connections.          Channel bind = Bootstrap.bind (new inetsocketaddress (8000)); SYSTEM.OUT.PRINTLN ("Server has started, listening port:" + bind.getlocaladdress () + ", waiting for client to register ...)      "); } private static Class Serverhandler extends Simplechannelhandler {@Override public void message Received (Channelhandlercontext ctx, messageevent e) throws Exception {if (E.getmessage () instanceof String)                  {String message = (string) e.getmessage ();                    SYSTEM.OUT.PRINTLN ("Client Sent:" + message);                    E.getchannel (). Write ("Server received just sent:" + message); System.out.println ("\ n wait for client input ...              ");          } super.messagereceived (CTX, E); } @Override public void Exceptioncaught (Channelhandlercontext ctx, exceptionevent e) throws Exception          {Super.exceptioncaught (CTX, E);     }       @Override public void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Exception { System.out.println ("There is a client registered up ...              ");              System.out.println ("Client:" + E.getchannel (). getremoteaddress ());              System.out.println ("Server:" + E.getchannel (). getlocaladdress ()); System.out.println ("\ n wait for client input ...              ");          Super.channelconnected (CTX, E);  }      }  }


Client:

Java code
Package me.hello.netty;  Import Org.jboss.netty.bootstrap.ClientBootstrap;  Import org.jboss.netty.channel.*;  Import Org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;  Import Org.jboss.netty.handler.codec.string.StringDecoder;    Import Org.jboss.netty.handler.codec.string.StringEncoder;  Import Java.io.BufferedReader;  Import Java.io.InputStreamReader;  Import java.net.InetSocketAddress;    Import java.util.concurrent.Executors;  /** * God Bless you!          * Author:fangniude * date:2013-07-15 * * * public class Nettyclient {public static void main (string[] args) {          Configure the client. Clientbootstrap bootstrap = new Clientbootstrap (New Nioclientsocketchannelfactory (Executors.newcachedthreadpool (),            Executors.newcachedthreadpool ()));          Set up the default event pipeline. Bootstrap.setpipelinefactory (New Channelpipelinefactory () {@Override public channelpipeline get Pipeline () throws Exception {                 Return Channels.pipeline (New Stringdecoder (), New Stringencoder (), New ClientHandler ());            }          });          Start the connection attempt.            Channelfuture future = Bootstrap.connect (new inetsocketaddress ("localhost", 8000));          Wait until the connection is closed or the connection attempt fails.            Future.getchannel (). Getclosefuture (). awaituninterruptibly ();          Shut down thread pools to exit.      Bootstrap.releaseexternalresources (); } private static class ClientHandler extends Simplechannelhandler {private BufferedReader sin = new Buffe            Redreader (New InputStreamReader (system.in));              @Override public void messagereceived (Channelhandlercontext ctx, messageevent e) throws Exception {                  if (E.getmessage () instanceof String) {String message = (string) e.getmessage ();                    SYSTEM.OUT.PRINTLN (message); E.getchannel (). Write (Sin.readline ()); System.out.println ("\ n wait for client input ...              ");          } super.messagereceived (CTX, E); } @Override public void channelconnected (Channelhandlercontext ctx, channelstateevent e) throws Except Ion {System.out.println ("Already connected to server ....              ");              System.out.println ("\ n Please enter the information to be sent:");                Super.channelconnected (CTX, E);          E.getchannel (). Write (Sin.readline ());  }      }  }


Netty Overall architecture



Netty Components

ChannelFactory

Boss

Worker

Channel

Channelevent

Pipeline

Channelcontext

Handler

Sink

Server-Side Core class

Nioserversocketchannelfactory

Nioserverbosspool

Nioworkerpool

Nioserverboss

Nioworker

Nioserversocketchannel

Nioacceptedsocketchannel

Defaultchannelpipeline

Nioserversocketpipelinesink

Channels

ChannelFactory

Channel factory, very important class

Save related parameters for startup

Nioserversocketchannelfactory

Nioclientsocketchannelfactory

Niodatagramchannelfactory

It's nio, and Oio and Local.

Selectorpool

Selector's thread pool

Nioserverbosspool Default thread Count: 1

Nioclientbosspool 1

Nioworkerpool 2 * Processor

Niodatagramworkerpool

Selector

Selectors, very core components

Nioserverboss

Nioclientboss

Nioworker

Niodatagramworker

Channel

Channel

Nioserversocketchannel

Nioclientsocketchannel

Nioacceptedsocketchannel

Niodatagramchannel

Sink

Responsible for interacting with the underlying

such as Bind,write,close, etc.

Nioserversocketpipelinesink

Nioclientsocketpipelinesink

Niodatagrampipelinesink

Pipeline

Responsible for maintaining all handler.

Channelcontext

A Channel One, the middleware of handler and pipeline.

Handler

Processor for channel events

Channelpipeline





Excellent design----Event-driven



Excellent design----threading model



Precautions

Position when decoding

The closing of the channel

More Handler

The closing of the channel

The channel that runs out can be closed directly;

1, channelfuture Plus listener

2, Writecomplete

It doesn't work for a while, you can close it.

Timeouthandler

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

Netty Getting Started Tutorial

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.