Netty Getting started two: developing the first Netty application

Source: Internet
Author: User

Since it's an introduction, let's write a simple demo here, where the client sends a string to the server side, and the server receives the string and sends it back to the client.

2.1. Configure the development environment

1. Install JDK2. Go to the official website to download the jar package (or build it via POM) 2.2, understand the Netty client and servera Netty application model, as shown, but it is important to understand that the server we write automatically handles multi-client requests, and in theory, the ability to handle concurrency depends on our system configuration and the limits of the JDK.    
    1. Client connects to server side
    2. Establish a link to send/Receive data
    3. Server-side processing of all client requests
Here is an image of the metaphor to describe the Netty client and server-side interaction mode, compare you to a customer, the mountain compared to a server, you go to the mountain, is the link with the mountain, you shouted to Alexander, on behalf of the mountain sent data, your shout through the reflection of the mountains to form an echo, This echo is the response data of the server. If you can leave, the link is broken, and of course you can come back. Once a lot of people shouted to the mountains, their shouts will certainly get the response of the mountain. 2.3 Write a netty ServerA nettyserver program consists of two main parts:
    • BootsTrapping: Configuring server-side Basic information
    • Serverhandler: True business logic processing
the process of 2.3.1 bootstrapping:
Package Nettydemo.echo.server;import Io.netty.bootstrap.serverbootstrap;import io.netty.channel.ChannelFuture; Import Io.netty.channel.channelinitializer;import Io.netty.channel.eventloopgroup;import Io.netty.channel.nio.nioeventloopgroup;import Io.netty.channel.socket.socketchannel;import Io.netty.channel.socket.nio.nioserversocketchannel;import Java.net.inetsocketaddress;import Nettydemo.echo.handler.echoserverhandler;public class Echoserver {private static final int port = 8080;public void Start ( ) throws Interruptedexception {Serverbootstrap b = new Serverbootstrap ();//boot helper Eventloopgroup group = new NIOEVENTLOOPG Roup ();//by NIO to receive connections and process connection try {B.group (group); B.channel (nioserversocketchannel.class);// Set the channelb.localaddress of the NIO type (new Inetsocketaddress (port));//Set the Listener Port B.childhandler (new channelinitializer< Socketchannel> () {///a channelprotected void Initchannel (Socketchannel ch) throws Exception {///is created when a connection arrives Pipeline manages handler in the channel, adding a handler to the channel queue to process the business ch.pipeline (). ADdlast ("MyHandler", New Echoserverhandler ());}); Channelfuture f = b.bind (). sync ();//configuration complete, start binding server, block by calling Sync Sync method until bind succeeds System.out.println ( EchoServer.class.getName () + "started and listen on" + F.channel (). localaddress ()); F.channel (). Closefuture (). sync (); /The application will wait until the channel closes} catch (Exception e) {e.printstacktrace ();} finally {group.shutdowngracefully (). sync ();// Close Eventloopgroup, releasing all resources including the created thread}}public static void Main (string[] args) {try {new Echoserver (). Start ();} catch ( Interruptedexception e) {e.printstacktrace ();}}}
1. Create a Serverbootstrap instance
2. Create a eventloopgroup to handle various events, such as processing link requests, sending received data, and so on.
3. Define the local inetsocketaddress (port) so that the server binds
4. Create a childhandler to process each link request
5. Call the Serverbootstrap.bind () method to bind the server after all is ready
2.3.2 Business logic Serverhandler:
To process the received data, we must inherit the Channelinboundhandleradapter interface, rewrite the Messagereceive method inside, and the method will be called whenever the data arrives (usually an array of type Byte). We are here to write our business logic:
Package Nettydemo.echo.handler;import Io.netty.buffer.unpooled;import Io.netty.channel.ChannelFutureListener; Import Io.netty.channel.channelhandlercontext;import Io.netty.channel.channelinboundhandleradapter;import io.netty.channel.channelhandler.sharable;/** * Sharable Indicates that this object is shared between channel * Handler class is our specific business class * */@Sharable// Annotation @sharable allows it to share public class Echoserverhandler extends channelinboundhandleradapter{public void between channels Channelread (Channelhandlercontext ctx, Object msg) {System.out.println ("Server received data:" + msg); Ctx.write (msg);//write Back data,} public void Channelreadcomplete (Channelhandlercontext ctx) {Ctx.writeandflush ( Unpooled.empty_buffer)//flush All data that is written back. AddListener (Channelfuturelistener.close); When flush is complete, close the channel} public void Exceptioncaught (Channelhandlercontext ctx,throwable cause) {Cause.printstacktrace ( );//catch Exception information ctx.close ();//Close channel when an exception occurs}}

2.3.3 About exception handling:
We also rewrite the Exceptioncaught method in the above procedure, which is the processing when the exception occurs.
2.4 Write a Netty Client
Generally a simple client will play the following roles:
    1. Connect to Server
    2. Writing data to the server
    3. Waiting for server to return data
    4. Close connection
the process of 4.4.1 bootstrapping:
Similar to the server side, except that the client side specifies both the IP and port of the connection host.
Package Nettydemo.echo.client;import Io.netty.bootstrap.bootstrap;import Io.netty.channel.channelfuture;import Io.netty.channel.channelfuturelistener;import Io.netty.channel.channelinitializer;import Io.netty.channel.eventloopgroup;import Io.netty.channel.nio.nioeventloopgroup;import Io.netty.channel.socket.socketchannel;import Io.netty.channel.socket.nio.niosocketchannel;import Java.net.inetsocketaddress;import Nettydemo.echo.handler.echoclienthandler;public class EchoClient {private final String host;private Final int port;public echoclient (string host, int port) {this.host = Host;this.port = port;} public void Start () throws Exception {Eventloopgroup group = new Nioeventloopgroup (); try {Bootstrap b = new Bootstrap (); b. Group (group); B.channel (Niosocketchannel.class); B.remoteaddress (new Inetsocketaddress (host, port); B.handler (new Channelinitializer<socketchannel> () {public void Initchannel (Socketchannel ch) throws Exception {Ch.pipeline (). AddLast (New Echoclienthandler ());}); ChanNelfuture f = b.connect (). sync (); F.addlistener (new Channelfuturelistener () {public void Operationcomplete ( Channelfuture future) throws Exception {if (future.issuccess ()) {SYSTEM.OUT.PRINTLN ("Client Connected");} ELSE{SYSTEM.OUT.PRINTLN ("Server attemp failed"); Future.cause (). Printstacktrace ();}}); F.channel (). Closefuture (). sync (); finally {group.shutdowngracefully (). sync ();}} public static void Main (string[] args) throws Exception {new Echoclient ("127.0.0.1", 3331). Start ();}}
1. Create a Serverbootstrap instance
2. Create a eventloopgroup to handle various events, such as processing link requests, sending received data, and so on.
3. Define a remote inetsocketaddress so that the client connects
4. Once the connection is complete, handler will be executed once
5. Call the Serverbootstrap.connect () method after all is ready to connect to the server 4.4.2 Business logic ClientHandler:
We also inherit a simplechannelinboundhandler to implement our client, and we need to rewrite three of these methods:
package Nettydemo.echo.handler;import Io.netty.buffer.bytebuf;import Io.netty.buffer.bytebufutil;import Io.netty.buffer.unpooled;import Io.netty.channel.channelhandlercontext;import Io.netty.channel.simplechannelinboundhandler;import Io.netty.channel.channelhandler.sharable;import Io.netty.util.CharsetUtil, @Sharablepublic class Echoclienthandler extends Simplechannelinboundhandler<bytebuf > {/** * This method is called after connecting to the server * */public void channelactive (Channelhandlercontext ctx) {ctx.write (Unpooled.copiedbuffer (" Netty rocks! ", Charsetutil.utf_8));} /** * This method calls * */public void channelRead0 (Channelhandlercontext ctx, bytebuf in) after receiving the server data {System.out.println ("Client re ceived: "+ bytebufutil.hexdump (in.readbytes (In.readablebytes ()));} /** * Snap to exception * */public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {cause.printstacktrace (); Ctx.close ();}} 

one of the things to note is channelRead0 () method, this method may receive some data fragments, such as the server sent 5 bytes of data, the client side can not guarantee that all received, such as the first time to receive 3 bytes, the second time to receive 2 bytes. We may also care about whether the order in which these fragments are received is consistent in the order in which they are sent, depending on what protocol, such as the TCP protocol-based byte stream, can guarantee the order. Also, in the client side of our business handler inherited is Simplechannelinboundhandler, and on the server side inherited is Channelinboundhandleradapter, then what is the difference between these two? The main difference is that Simplechannelinboundhandler automatically release the Bytebuffer resource (called Bytebuffer.release ()) that is consumed by the data after it receives the data. And why the server is not available, because we want the server to send the data requested by the client back, and the server side may not have finished writing the data before the Channelread method returns, so it cannot be automatically release.


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.