Preface
Recently interested in Netty, now the official recommended version is netty4.*, but throughout the network, most of it is about netty3.x knowledge.
The best way to learn is through the official documents to learn, system, thorough, authoritative, the disadvantage is English. This article, to do their own study Netty the first, the general idea and User guide for 4.x basically consistent, this article is not a strictly meaningful translation of the article. Here we go...
1. Preface
1.1 question
Now, we use common applications and libraries to communicate with each other. For example, we often use the HTTP client library to obtain information from a Web server and invoke the remote interface through Web services. However, generic protocols or implementations sometimes do not scale well. Just as we cannot use generic protocols for exchanging part of the information, such as: Huge files,e-mail, real-time information. We need a highly optimized protocol implementation to accomplish some special purpose. For example, you want to achieve a specialHTTP server to support AJAX-based chat applications, streaming media, large file transfer. You need to design and implement a complete new protocol, inevitably dealing with legacy protocols, without compromising performance and stability, how fast can a new protocol be implemented?
1.2 solution
Netty is committed to providing an asynchronous, event-driven network application framework that is fast-developing high-performance, scalable protocol server and client tools. In other words, Netty is a fast and easy-to-develop NIO client, a server-side network framework that simplifies and uses streaming network programming, such as TCP,UDP.
"Fast and easy" does not mean that Netty has maintainability and performance issues. It is perfect for providing ftp,smtp,http, binary and text-based protocol support. Some users may have discovered other network application frameworks that have the same kind of a. You may want to ask: Netty and their differences? This is a difficult question to answer, Netty is designed to provide the most appropriate API and implementation, will make your life easier.
2. Start
This section uses a few simple examples to quickly perceive the core structure of Netty. After reading this section, you can master Netty and write a client and server.
Get ready
JDK 1.6+
Latest version of Netty:
Maven Dependency
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
2.1 Write a Discard service
The simplest protocol, not ' Hello World ', but DISCARD . This protocol discards the received data and does not respond.
Protocol implementation, the only thing to do is to ignore all the data received, let's get started.
directly on handler, which handles I/O events from Netty.
package io.netty.examples.discard;import io.netty.buffer.bytebuf;import io.netty.channel.channelhandlercontext;import io.netty.channel.channelinboundhandleradapter;import Io.netty.util.referencecountutil;/** * handles a server-side channel. */public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1) @Override public void channelread ( CHANNELHANDLERCONTEXT&NBSP;CTX,&NBSP;OBJECT&NBSP;MSG) { // (2) // Discard the received data silently. ((BYTEBUF) msg). Release (); // (3) /* //can also be like this try { // do something with msg } finally { referencecountutil.release (msg); } */ } @Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) { // (4) // close the connection when an exception is raised. cause.printstacktrace (); ctX.close (); }}
1)DiscardServerHandler
Inherited ChannelInboundHandlerAdapter
,
实现了
ChannelInboundHandler
Interface. ChannelInboundHandler
provides several overridable event-handling methods. Now, inherit theChannelInboundHandlerAdapter,而不用自己实现handler接口。
2) rewrite channelRead
(), this method is called when new information is received. Information type is BYTEBUF
3) Implement the discard protocol, BYTEBUF is the Reference-counted object and must display the call release () to be released. It is necessary to remember that handler's responsibilities include releasing arbitrary reference-counted objects.
4) Exceptioncaught (), called when an exception occurs, an I/O exception, or handler handling exception. In general, the Exception Log can be logged here, and the error code is returned.
Here, half finished, then write main ()
, start server
package io.netty.examples.discard;import io.netty.bootstrap.serverbootstrap;import io.netty.channel.channelfuture;import io.netty.channel.channelinitializer;import io.netty.channel.channeloption;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 Io.netty.examples.discard.time.timeserverhandler;/** * discards any incoming data. */public class DiscardServer { private int port; public discardserver (Int port) { this.port = port; } public void run () throws Exception { EventLoopGroup Bossgroup = new&nBsp Nioeventloopgroup (); // (1) EventLoopGroup Workergroup = new nioeventloopgroup (); try { serverbootstrap b = New serverbootstrap (); // (2) b.group (Bossgroup, workergroup) .channel (Nioserversocketchannel.class) // (3) .childhandler (new channelinitializer<socketchannel> () { // (4) @Override public&nbSp;void initchannel (socketchannel ch) throws Exception { Ch.pipeline (). AddLast (New timeserverhandler ()); } }) .option ( channeloption.so_backlog, 128) // (5) .childoption (ChannelOption.SO_ Keepalive, true); // (6) // Bind and start to accept incoming connections. &nbSp; channelfuture f = b.bind (port). Sync (); // (7) // wait until the server socket is closed. // in this example, this does not happen, but you can do that to gracefully // shut down your server. f.channel (). Closefuture (). Sync (); } finally { workergroup.shutdowngracefully (); bossgroup.shutdowngracefully (); } &Nbsp; } public static void main (String[] args) throws exception { int port; if (args.length > 0) { port = integer.parseint (Args[0]); } else { port = 8080; } new discardserver (Port). Run (); }}
NioEventLoopGroup
is a multi-threaded processing I/O operation event Loop (this is an asynchronous mechanism feature) Netty provides multiple EventLoopGroup
, multi-mode support. In this example, we used 2 of them NioEventLoopGroup
.
The first one, called "Boss", receives incoming connections, the second is often called "worker", and once the boss receives the connection and registers the connection to the Worker,worker, the connection is processed. How many threads are used? , how many channel does Eventloopgroup have? Can be configured through the constructor function
ServerBootstrap
Is the Help class that establishes the server. You can use the channel to create the server directly, note that this creation process is very lengthy, most of the situation, you do not need to create directly.
Specifies the Nioserversocketchannel class, which is used in the initialization of the channel when receiving a new access connection.
This handler is called when the channel is initialized. Channelinitializer is a handler specifically configured for the new channel, typically channelpipeline for channel configuration. When the business is complex, more handler to pipeline are added.
You can set parameters that affect the channel implementation, such as KeepAlive.
option()
The effect of receiving incoming connections is that the 的NioServerSocketChannel
;childOption()
channel from the parent Serverchannel is distributed, in this case NioServerSocketChannel
Make sure the work is ready.
Test with Telnet.
Enter Telnet 127.0.0.1 8080
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/82/CC/wKioL1dhJzahlRuaAAAJeL7rMjk054.png "title=" 11.png "alt=" Wkiol1dhjzahlruaaaajel7rmjk054.png "/>
Because it is discard protocol, one does not respond, the two service side also did not output. Pass the test, can only confirm that the service started properly.
Adjust the handler logic and modify the Channelread () method.
@Overridepublic void Channelread (Channelhandlercontext ctx, Object msg) {bytebuf in = (BYTEBUF) msg; try {while (in.isreadable ()) {//(1) System.out.print (char) in.readbyte ()); System.out.flush (); }} finally {Referencecountutil.release (msg);//(2)}}
Pending additions
This article is from a "simple" blog, so be sure to keep this source http://dba10g.blog.51cto.com/764602/1789639
netty4.x User Guide