Introduction to the "Netty" NIO framework Netty

Source: Internet
Author: User
Tags throwable

Netty Introduction

Netty is a Java open source framework provided by JBoss. Netty provides asynchronous, event-driven network application frameworks and tools for rapid development of high-performance, high-reliability network servers and client programs.

In other words, Netty is a NIO-based client, server-side programming framework that uses Netty to ensure that you can quickly and easily develop a network application, such as a client that implements some kind of protocol, a service-side application. Netty quite simplifies and streamlines the programming of Web applications, for example, the development of socket services for TCP and UDP.

Website address: http://netty.io/

Usage Scenarios

Netty's ability to become the mainstream NIO framework is because it has the following advantages:

    • NIO's class libraries and APIs are more difficult to use, Netty are packaged and easy to get started
    • High performance, powerful, multi-codec support, multi-mainstream protocol support
    • Mature, stable, already in use in multiple large frameworks (DUBBO,ROCKETMQ,HADOOP,MYCAT,SPRING5)
    • .....
Easy to get Started

We write a server and client, the client sends a message to the server, the message is passed by string, the server receives the message sent by the client, and then replies to a message.

First write the service-side code:

 Public classImserver { Public voidRunintPort) {Eventloopgroup Bossgroup=NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Serverbootstrap Bootstrap=NewServerbootstrap (); Bootstrap.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Childhandler (NewChannelinitializer<socketchannel>() {@Override Public voidInitchannel (Socketchannel ch)throwsException {ch.pipeline (). AddLast ("Decoder",NewStringdecoder ()); Ch.pipeline (). AddLast ("Encoder",NewStringencoder ()); Ch.pipeline (). AddLast (NewServerstringhandler ()); }}). option (Channeloption.so_backlog,128). Childoption (Channeloption.so_keepalive,true); Try{channelfuture F=Bootstrap.bind (port). sync ();        F.channel (). Closefuture (). sync (); } Catch(interruptedexception e) {e.printstacktrace (); } finally{workergroup.shutdowngracefully ();        Bossgroup.shutdowngracefully (); }    }}
    • The configuration of the service through Serverbootstrap, and the socket parameters can be set through Serverbootstrap.
    • The Group method Associates two thread groups, Nioeventloopgroup is the thread pool used to handle I/O operations, the first is called "Boss", which is used to accept client connections, and the second is called "Worker", which handles read and write operations of client data. Of course you can also use only one nioeventloopgroup to handle the connection and read and write at the same time, the Bootstrap.group () method supports one parameter.
    • Channel Designation NiO method
    • Childhandler is used to configure the specific data processing method, can refer to specifying decoder, processing data handler
    • Bind Port Start Service

Message processing:

 /**   * message processing   */ public  class  Serverstringhandler extends   Channelinboundhandleradapter {@Override  public  void   Channelread (Channelhandlercontext ctx, Object msg) {System.err.printl        N ( "server:" + msg.tostring ());    Ctx.writeandflush (msg.tostring ()  + "Hello"  public  void   Exceptioncaught (Channelhandlercontext ctx, throwable cause) {cause.printstacktrace ();    Ctx.close (); }}

Start the service, specifying a port of 8888:

 Public Static void Main (string[] args) {    int port = 8888;     New Thread ((), {        new  imserver (). Run (port);    }). Start ();}

To write the Client connection logic:

 Public classimconnection {Privatechannel Channel;  PublicChannel Connect (String host,intPort)        {Doconnect (host, Port); return  This. Channel; }    Private voidDoconnect (String host,intPort) {Eventloopgroup Workergroup=NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap ();            B.group (Workergroup); B.channel (Niosocketchannel.class); B.option (Channeloption.so_keepalive,true); B.handler (NewChannelinitializer<socketchannel>() {@Override Public voidInitchannel (Socketchannel ch)throwsException {ch.pipeline (). AddLast ("Decoder",NewStringdecoder ()); Ch.pipeline (). AddLast ("Encoder",NewStringencoder ()); Ch.pipeline (). AddLast (NewClientstringhandler ());            }            }); Channelfuture F=B.connect (host, port). sync (); Channel=F.channel (); } Catch(Exception e) {e.printstacktrace (); }    }}

Client Message Processing:

/***/Publicclassextends  channelinboundhandleradapter {    @Override      Public void Channelread (Channelhandlercontext ctx, Object msg) {        System.out.println ("client:" +  Msg.tostring ());    }    @Override    publicvoid  exceptioncaught (Channelhandlercontext ctx, Throwable Cause) {        cause.printstacktrace ();        Ctx.close ();    }}

The client initiates the portal and then sends a message to the server:

 Public Static void Main (string[] args) {    = "127.0.0.1";     int port = 8888;     New imconnection (). Connect (host, port);    Channel.writeandflush ("Greensniper");}

The test steps are as follows:

    1. Start the service side first
    2. Start the client, send a message
    3. server receives message, console has outputserver:greenSniper
    4. Client receives server reply message, console has outputclient:greenSniper你好

Introduction to the "Netty" NIO framework Netty

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.