Netty in Action Chinese version-chapter II: First Netty program

Source: Internet
Author: User

This chapter describes

    • Get the latest version number for Netty4
    • Setting up the execution environment to build and execute Netty programs
    • Create a Netty-based server and client
    • Intercepting and Handling exceptions
    • Preparation and execution of Nettyserver and client
This chapter will introduce the core concept of Netty, the hard-hearted concept of learning how Netty is to intercept and handle anomalies. For readers who have just started learning Netty. It is very helpful to use Netty's exception interception mechanism to debug program problems. Some other core concepts are also described in this chapter. such as server and client start-up and separation of the channel handlers. This chapter learns some basics for in-depth learning in later chapters.

This chapter will write a Netty-based server and client to communicate with each other, we first set up the Netty development environment.

2.1 The process for setting up the development environment for setting up the development environment is as follows:
    • Installing jdk7,http://www.oracle.com/technetwork/java/javase/archive-139210.html
    • Download Netty Package, http://netty.io/
    • Install Eclipse
"Netty in action" is much more descriptive and useless. There's not much to say here. This series of blogs will use Netty4. Need jdk1.7+
2.2 Nettyclient and Server overview This section will guide you through building a complete nettyserver and client. Under normal circumstances. You might just care about writing the server, such as a httpserver client is a browser. Then in this example, if you implement both server and client at the same time.        You will be more clear about their principles. A working diagram of a Netty program such as the following

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvywjjx2tleq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

    1. Client connects to server
    2. Send or receive data after a connection is established
    3. Server handles all client connections

As you can see, the server writes data to the client and handles concurrent connections for multiple clients. Theoretically, limiting the performance of the program only has the system resources and the JVM. To make it easy to understand, here's a sample of life. Shout loudly in the valleys or mountains, and you will hear the echoes. Echoes are returned by mountains; In this example, you are the client. The mountain is the server. The act of shouting is similar to a nettyclient sending data to the server, and hearing the Echo is similar to the server returning the same data to you, leaving the valley disconnected. But you can go back and re-connect the server and be able to send a lot of other data.


Although returning the same data to the client is not a typical example. However, the transfer of data between the client and server is the same as this example. The sample examples in this chapter prove this and they will become more and more complex.
The next few sections will take you through the Netty-based client and server answer program.


2.3 Writing an Answer server

Writing a nettyserver consists mainly of two parts:

    • Configure server features, such as threads, port
    • Implement the server handler, which includes the business logic that determines what to do when there is a request to connect or receive data
2.3.1 Starting the server

Start the server by creating a Serverbootstrap object. Then configure the relevant options for this object. such as port, threading mode, event loop, and logic handlers to handle business logic (here is a simple answer server example)

Package Netty.example;import Io.netty.bootstrap.serverbootstrap;import Io.netty.channel.channel;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.nio.nioserversocketchannel;public Class Echoserver {private final int port;public echoserver (int port) {this.port = port;} public void Start () throws Exception {Eventloopgroup group = new Nioeventloopgroup (); try {//create serverbootstrap Instanc Eserverbootstrap B = new Serverbootstrap ();//specifies NIO Transport, local socket ADDRESS//ADDS handler to channel Pipeli Neb.group (Group). Channel (Nioserversocketchannel.class). LocalAddress (Port). Childhandler (New Channelinitializer <Channel> () {@Overrideprotected void Initchannel (Channel ch) throws Exception {Ch.pipeline (). AddLast (New Echoserverhandler ());}); /binds server, waits for server to close, and releases resourceschannelfuture f = b.bind (). Sync(); System.out.println (EchoServer.class.getName () + "started and listen on?" + F.channel (). localaddress ()); F.channel (). Closefuture (). sync ();} finally {group.shutdowngracefully (). sync ();}} public static void Main (string[] args) throws Exception {new Echoserver (65535). Start ();}}
As can be seen from the simple server example above, starting server should first create a Serverbootstrap object. Because of the use of NIO, Nioeventloopgroup is specified to accept and process new connections. Specify the channel type Nioserversocketchannel, set Inetsocketaddress to have the server listen on a port waiting for a client connection.
Next, call Childhandler to specify the Channelhandler that is called after the connection is placed. This method passes the Channelinitializer type of the parameter. Channelinitializer is an abstract class, so you need to implement the Initchannel method, which is used to set the Channelhandler.


Finally, bind server waits until the binding is complete. The call to the sync () method is blocked until the server is finished binding, and then the server waits for the channel to close. Due to the use of sync (), the shutdown operation is also blocked. Now you can shut down Eventloopgroup and release all resources, including the created thread.


In this example, NIO is used because it is the most commonly used transport mode at the moment. You may be using NIO for a very long time. But you can choose a different transmission implementation. Like what. This sample is transmitted using OIO mode, you need to specify Oioserversocketchannel. Multiple transports are implemented in the Netty framework and are described later.
This section highlights the following:

    • Create a Serverbootstrap instance to boot the binding and start the server
    • Create Nioeventloopgroup objects to handle events, such as accepting new connections, receiving data, writing data, and so on
    • Specifies Inetsocketaddress. Server listens on this port
    • Set Childhandler to run all connection requests
    • is set to complete, and finally the Serverbootstrap.bind () method is called to bind the server
2.3.2 implements the server business logic Netty using futures and callback concepts. It's designed to allow you to handle different types of events. A more specific introduction will be described later in the chapter. But we are able to receive data.

Your channel handler must inherit Channelinboundhandleradapter and rewrite the Channelread method, which is called at any time to receive data, in which case it receives bytes.


The following is the implementation of handler, in fact, the function is to return the client to the server data to the client:

Package Netty.example;import Io.netty.buffer.unpooled;import Io.netty.channel.channelfuturelistener;import Io.netty.channel.channelhandlercontext;import Io.netty.channel.channelinboundhandleradapter;public Class Echoserverhandler extends Channelinboundhandleradapter {@Overridepublic void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {System.out.println ("Server Received:" + msg); Ctx.write (msg);} @Overridepublic void Channelreadcomplete (Channelhandlercontext ctx) throws Exception {Ctx.writeandflush ( Unpooled.empty_buffer). AddListener (Channelfuturelistener.close);} @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception { Cause.printstacktrace (); Ctx.close ();}}
Netty uses multiple channel handler to achieve separation of event processing, due to the ability to join, update, and delete business logic processing handler.

Handler is very easy, and each of its methods can be rewritten, and all of its methods only have channelread methods that must be rewritten. The 2.3.3 catch exception override Channelhandler's Exceptioncaught method captures the exception of the server, which, for example, forces shutdown after the client connects to server, and the server throws a "client host forced shutdown error". You can handle exceptions by overriding the Exceptioncaught method, such as closing channelhandlercontext after an exception occurs. 2.4 The client server that wrote the responder was written. Now write a client connection server. The client of the responder contains the following steps:

    • Connect to Server
    • Write data to Server
    • Wait for the server to return the same data
    • Close connection
2.4.1 booting the client directs the client to boot and boot the server very similarly, the client needs to specify both host and port at the same time to tell the client which server to connect to. Look at the following code:
Package Netty.example;import Io.netty.bootstrap.bootstrap;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.niosocketchannel;import Io.netty.example.echo.echoclienthandler;import Java.net.inetsocketaddress;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. Channel (Niosocketchannel.class). remoteaddress (New Inetsocketaddress (host, Port)). Handler (new Channelinitializer<socketchannel> () {@Overrideprotected void Initchannel (Socketchannel ch) throws Exception { Ch.pipeline (). AddLast (New Echoclienthandler ());}); Channelfuture f = b.connect (). sync (); F.channel (). ClosEfuture (). sync ();} finally {group.shutdowngracefully (). sync ();}} public static void Main (string[] args) throws Exception {new echoclient ("localhost", 20000). Start ();}}
Creating a client to start consists of the following steps:
    • Create a Bootstrap object to boot the client
    • To create a Eventloopgroup object and set it to Bootstrap, Eventloopgroup can be understood as a thread pool. This thread pool is used to process connections, accept data, send data
    • Create the inetsocketaddress and set it to bootstrap. Inetsocketaddress is the server address of the specified connection
    • Joining a channelhandler,client will be run when the server is successfully connected
    • Call Bootstrap.connect () to connect to the server
    • Finally close eventloopgroup to release resources
2.4.2 implementation of the client's business logic client's business logic is still very easy to implement, and more complex usage methods will be described in later chapters.

As with the Channelhandler of the authoring server, here you define a Channelhandler that inherits Simplechannelinboundhandler to handle the business, and three ways to handle the events of interest by overriding the parent class:

    • Channelactive (): Called after client connects to server
    • ChannelRead0 (): Called after receiving data from server
    • Exceptioncaught (): Called when an exception occurs
Implementation code such as the following
package Netty.example;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.util.charsetutil;public class Echoclienthandler extends Simplechannelinboundhandler<bytebuf> {@ overridepublic void Channelactive (Channelhandlercontext ctx) throws Exception {Ctx.write (Unpooled.copiedbuffer (" Netty rocks! ", Charsetutil.utf_8));} @Overrideprotected void ChannelRead0 (Channelhandlercontext ctx, Bytebuf msg) throws Exception {System.out.println (" Client Received: "+ bytebufutil.hexdump (msg.readbytes (Msg.readablebytes ())));} @Overridepublic void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception { Cause.printstacktrace (); Ctx.close ();}} 
Perhaps you would ask why Simplechannelinboundhandler is used here instead of using Channelinboundhandleradapter? The main reason is that Channelinboundhandleradapter is responsible for releasing resources after the message has been processed.

This will call Bytebuf.release () to release the resource. Simplechannelinboundhandler will release the message after the channelRead0 is finished, which is achieved by Netty processing all the messages Channelhandler the Referencecounted interface.


Why not use Simplechannelinboundhandler in the server?        Because the server is going to return the same message to the client, the message read to the call cannot be freed until the server finishes the write operation, because the write operation is asynchronous, and once the write operation is complete, the message is released voluntarily in Netty. The client has been written, so let's take a look at the test.
2.5 Compiling and executing the Echo (answer) program client and server

Note thatNetty4 needs to be jdk1.7+.

I test, can be normally executed.

2.6 Summary

This chapter describes how to write server and client and send data communication based on a simple netty. It describes how to create the server and client as well as the Netty exception handling mechanism.


Netty in Action Chinese version-chapter II: First Netty program

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.