"Netty in Action Chinese version" chapter II: the First Netty program

Source: Internet
Author: User
Tags throwable

Note: This article is from "Netty in Action" a book;

Note: I original translation, reproduced please indicate the source!


This chapter describes

    • Get the latest version of Netty4
    • Set up the run environment to build and run the Netty program
    • Create a Netty-based server and client
    • Intercepting and Handling exceptions
    • Writing and running Netty servers and clients
This chapter will briefly introduce the core concept of Netty, the hard-hearted concept is to learn how Netty is to intercept and deal with anomalies, for the readers who have just started learning Netty, using the Netty of the exception interception mechanism to debug program problems is very helpful. Other core concepts such as server and client startup and the separation of the channel handlers are also described in this chapter. 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 steps to set up the development environment for the development environment are 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" described more, no use, there is not much to say. This series of blogs will use Netty4 and need jdk1.7+
2.2 Netty Client and Server overview This section will guide you through building a complete Netty server and client. In general, you may only be interested in writing a server, such as a client of an HTTP server is a browser.        Then in this example, if you implement both the server and the client, you will be more clear about their principles. A working diagram of a Netty program is as follows
    1. Client connects to server
    2. Send or receive data after a connection is established
    3. The server handles all client connections

As you can see, the server writes data to the client and handles concurrent connections from multiple clients. Theoretically, there are only system resources and JVMS that restrict program performance. To make it easy to understand, here's an example of life, shouting in a valley or a mountain, you hear echoes, echoes are mountains back, in this case you are the client, the mountain is the server. Shouting behavior is similar to a Netty client 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 to reconnect the server and send more data.

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

Writing a Netty server consists of two main parts:

    • Configure server features, such as threads, ports
    • Implement a server handler that contains 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, and then configure the relevant options for the object, such as port, thread mode, event loop, and add logic handlers to handle the 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 you can see from the simple server example above, the boot server should first create a Serverbootstrap object because it uses NIO, so specify nioeventloopgroup to accept and process the new connection. 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, this method passes the Channelinitializer type parameter, Channelinitializer is an abstract class, So the Initchannel method needs to be implemented, and this method is used to set the Channelhandler.
Finally, the binding server waits until the binding is complete, the call to the sync () method blocks until the server finishes binding, and the server waits for the channel to close, because sync () is used, so the shutdown operation is also blocked. Now you can close Eventloopgroup and release all resources, including the created thread.
This example uses NIO, because it is the most commonly used transmission mode, you may use NIO for a long time, but you can choose a different transport implementation. For example, this example is transmitted using the Oio method, and 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
    • Specify inetsocketaddress, the server listens on this port
    • Set Childhandler to perform all connection requests
    • is set, and finally the Serverbootstrap.bind () method is called to bind the server
2.3.2 implements the server business logic Netty uses futures and callback concepts, its design allows you to handle different types of events, more detailed introduction will be described later in the chapter, but we can receive data. Your channel handler must inherit Channelinboundhandleradapter and rewrite the Channelread method, which is called at any time to receive data, and in this case, bytes are received.
The following is the implementation of the handler, which is implemented by returning the data that the client sends to the server 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, because the business logic processing handler can be added, updated, and deleted very easily. Handler is simple, each of its methods can be rewritten, and all of its methods are only channelread methods that must be rewritten. 2.3.3 Catch Exception Override Channelhandler Exceptioncaught method can catch the server's exception, such as the Client Connection server forced shutdown, the server throws "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 writing the responder is written, now write a client connection server. The client of the responder includes the following steps:
    • Connecting to a server
    • Write data to the server
    • Wait for the receiving server to return the same data
    • Close connection
2.4.1 booting the client to boot the client is similar to booting the server, and the client needs to specify both host and port 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 ();}}
Create a client that starts with the following steps:
    • Create a Bootstrap object to boot the startup client
    • To create a Eventloopgroup object and set it to Bootstrap, Eventloopgroup can be understood as a thread pool that is used to process connections, accept data, send data
    • Create inetsocketaddress and set to Bootstrap, Inetsocketaddress is the server address of the specified connection
    • Add a channelhandler that will be executed after the client has successfully connected to the server
    • Call Bootstrap.connect () to connect to the server
    • Finally close eventloopgroup to release resources
2.4.2 the implementation of the business logic of the client's business logic client is still simple, and the more complex usage will be described in more detail later in the chapter. As with the Channelhandler of the authoring server, a Channelhandler that inherits Simplechannelinboundhandler is customized to handle the business, and the events of interest are handled by overriding the three methods of the parent class:
    • Channelactive (): The client is called after connecting to the server
    • ChannelRead0 (): Called after data has been received from the server
    • Exceptioncaught (): Called when an exception occurs
The implementation code is as follows
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 messages have been processed. This will call Bytebuf.release () to release the resource. Simplechannelinboundhandler will release the message after the completion of the channelRead0, which is achieved by Netty processing all the messages Channelhandler the Referencecounted interface.
Why not use Simplechannelinboundhandler in the server?        Because the server is returning the same message to the client, the message read to the call cannot be freed until the server performs a write operation, because the write operation is asynchronous and the message is automatically released in Netty once the write operation is complete. The client has finished writing, let's test it.
2.5 Compiling and running the Echo (answer) program client and server

Note thatNetty4 needs jdk1.7+.

I test, can run normally.

2.6 Summary

This chapter describes how to write a simple Netty-based server and client and send data for communication. Describes how to create exception handling mechanisms for servers and clients as well as for 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.