Netty 3.1 Chinese User manual (二)-Start

Source: Internet
Author: User
Tags api manual shallow copy jboss

Original address: http://www.jboss.org/file-access/default/members/netty/freezone/guide/3.1/html_single/index.html

Netty 3.1 Chinese User manual (i)-preface

Netty 3.1 Chinese User manual (二)-Start

Netty 3.1 Chinese User manual (iii)-Overview of the architecture

Chapter I. Start


This chapter will be centered around the core structure of Netty, with a few simple examples to help you understand the use of netty more quickly. When you finish reading this chapter, you will have the ability to use Netty to complete client and server development.

If you prefer a top-down approach, you can first complete the second chapter: Architecture Overview, and then come back here.

1.1. Before beginning


The two minimum requirements for running the sample program in this chapter are the latest version of the Netty program and JDK 1.5 or later. The latest version of the Netty program can be downloaded on the project download page. Download the correct version of the JDK to your preferred JDK site.

Is that enough? In fact, you will find that these two conditions are enough for you to complete the development of any agreement. If not, please contact the Netty Project community to let us know what is missing.

Eventually, but not at least, refer to the API manual when you want to learn more about the classes described in this chapter. For your convenience, all of the class names in this document are connected to the online API manual. In addition, if you have any error messages in this document, whether it is a syntax error, typographical errors, or you have better suggestions, please do not hesitate to contact the Netty Project community immediately.

1.2. Abandonment of protocol services


The simplest protocol in the world is not "hello,world!." But to abandon the agreement. This is a protocol that discards any data received and does not respond in any way.

To implement the Discard Protocol (discard protocol), you only need to ignore any data you receive. Let's start directly from the processor (handler) implementation, which handles all I/O events Netty. Java code    package org.jboss.netty.example.discard;      @ Channelpipelinecoverage ("All") 1   public class discardserverhandler extends  simplechannelhandler {2           @Override         public void messagereceived (Channelhandlercontext ctx, messageevent e)  {3       }           @Override         public void exceptioncaught (channelhandlercontext ctx,  Exceptionevent e)  {4           e.getcause (). Printstacktrace ();                      channel ch = e.getchannel ();           ch.close ();          }  

Code Description 1 Channelpipelinecoverage notes a type of processor that indicates whether a processor can be shared by multiple channel channels (and associated with Channelpipeline). Discardserverhandler does not handle any stateful information, so the annotation here is "all."

2) Discardserverhandler inherited the Simplechannelhandler, which is also a channelhandler implementation. Simplechannelhandler provides a variety of event-handling methods that you can override. The immediate inheritance of Simplechannelhandler is sufficient and does not require you to complete a processor interface of your own.

3 Here we rewrite the Messagereceived event handling method. This method is invoked by a Messageevent event that receives client-transmitted data. In this example, we ignore any data received and use this to implement a discard protocol (discard protocol).

4 The Exceptioncaught event handling method is invoked by a Exceptionevent exception event that results from a netty I/O exception or an internal exception that is implemented by a processor. In most cases, the caught exception should be logged, and the channel channel should be closed in this method. Of course the approach to handling this anomaly may vary depending on your actual requirements, for example, you might send a response message that contains an error code before closing the connection.

So far, we've done half the development work of discarding protocol servers. The next thing to do is to complete a main method that can start this containing Discardserverhandler processor service.

  Java code    package org.jboss.netty.example.discard;      import  java.net.inetsocketaddress;   import java.util.concurrent.executors;      public class discardserver {          public static  void main (String[] args)  throws Exception {            ChannelFactory factory =                new NioServerSocketChannelFactory  (                         Executors.newcachedthreadpool (),                        executors.newcachedthreadpool ());         &Nbsp;     serverbootstrap bootstrap = new serverbootstrap  ( Factory);              DiscardServerHandler  Handler = new discardserverhandler ();            channelpipeline pipeline = bootstrap.getpipeline ();            pipeline.addlast ("handler",  handler);               bootstrap.setoption ("Child.tcpnodelay",  true);            bootstrap.setoption ("Child.keepalive",  true);              bootstrap.bind (new inetsocketaddress (8080));       }  }  

Code Description
1) ChannelFactory is a factory interface for creating and managing channel channels and their associated resources, which handles all I/O requests and generates corresponding I/O channelevent Channel events. Netty provides a variety of channelfactory implementations. Here we need to implement a service-side example, so we use the nioserversocketchannelfactory implementation. Another thing to note is that the factory is not responsible for creating I/O threads. You should specify the thread pool that the factory uses in its constructor, and the benefit is that you gain greater control over the threads used in your application environment, such as an application service that includes security management.

2) Serverbootstrap is a help class that sets the service. You can even set up a channel channel directly in this service. Note, however, that this is a tedious process that is not required in most cases.

3 Here, we add the Discardserverhandler processor to the default Channelpipeline channel. Any time a new connection is received by the server, a new Channelpipeline pipe object will be created, and all Channelhandler objects added here will be added to this new Channelpipeline pipe object. It's much like a shallow copy operation (a shallow-copy operation); all channel channels and their corresponding Channelpipeline instances share the same Discardserverhandler instance.

4 You can also set the configuration parameters for this channel implementation that we specify here. We are writing a TCP/IP service, so we run a set of socket options, such as Tcpnodelay and KeepAlive. Notice the "child." that we added in the configuration options. Prefix. This means that this configuration entry only applies to the channel instance we receive, not to the Serversocketchannel instance. So you can set the parameters for a serversocketchannel like this:
Bootstrap.setoption ("Reuseaddress", true);

5) We continue. All that remains to be done is to bind the port used by the service and start the service. Here, we bind the 8080 ports on all the NIC (Nics,network interface cards) on the machine. Of course, you can now invoke the binding operation multiple times with different binding addresses.

Done. Now you have completed your first Netty based server program.

1.3. View received Data


Now that you've done your

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.