Getting started with Netty

Source: Internet
Author: User

Getting started with Netty

In the previous article titled Netty, we briefly described AIO, BIO, PIO, and nio and wrote a simple demo. However, this is simple and I can only handle it, especially NIO and AIO ).
Before starting netty's TimeServer development, let's review the process of NIO's server development:

  • 1. Create a ServerSocketChannel and configure it as non-blocking;
  • 2. bind the listener and configure TCP parameters, such as the backlog size;
  • 3. Create an independent IO thread for polling the Selector;
  • 4. Create a Selector, register the previously created ServerSocketChannel to the Selector, and listen to SelectionKey. ACEPT;
  • 5. Start the IO thread and run the Selector. select () method in the loop body to poll the ready Channel;
  • 6. when polling to a Channel in the ready state, you need to judge it. If it is in the OP_ACCEPT state, it indicates that it is accessed by a new client, then ServerSocketChannel is called. the accept () method accepts new clients;
  • 7. Set the newly accessed client link SocketChannel to non-blocking mode, and configure other TCP parameters;
  • 8. register the SocketChannel to the Selector and listen to the OP_READ operation bit;
  • 9. If the polling Channel is OP_READ, it indicates that a new ready data packet in the SocketChannel needs to be read, and a ByteBuffer object is constructed to read the data packet;
  • 10. If the polling Channel is OP_WRITE, it indicates that data has not been sent completely and you need to continue sending.

A simple NIO program requires more than 10 complex operations to complete the most basic message reading and sending. This is why I learned netty, next, let's take a look at how netty can easily write data to servers.
Here, I use IDEA 14 + Maven to write the TimeServer program in the previous article with netty. Here I use the Maven pom directly. xml to directly download the netty package (Maven is a project management tool that manages dependencies and supports automated testing, compilation, and construction. For specific Maven, please search by Baidu and google ).

/* TimeServer */

1 public class TimeServer {2 public void bind (int port) throws Exception {3/* configure the NIO thread group of the server */4 // NioEventLoopGroup class is a thread group, contains a group of NIO threads for processing network events 5 // (actually it is a Reactor thread group ). 6 // create two thread groups. One is the connection from the server to receive the client, and the other is the connection from the SocketChannel 7 // network read/write 8 EventLoopGroup bossGroup = new NioEventLoopGroup (); 9 EventLoopGroup WorkerGroup = new NioEventLoopGroup (); 10 11 try {12 // ServerBootstrap class, is the auxiliary startup class for starting the NIO server 13 ServerBootstrap B = new ServerBootstrap (); 14 B. group (bossGroup, WorkerGroup) 15. channel (NioServerSocketChannel. class) 16. option (ChannelOption. SO_BACKLOG, 1024) 17. childHandler (new ChildChannelHandler (); 18 19 // bind the port and wait for synchronization to succeed 20 ChannelFuture f = B. bind (port ). sync (); 21 22 // wait until the server listening port is closed 23 f. channel (). closeFuture (). sync (); 24} finally {25 // release thread pool resource 26 bossGroup. shutdownGracefully (); 27 WorkerGroup. shutdownGracefully (); 28} 29} 30 31 private class ChildChannelHandler extends ChannelInitializer <SocketChannel> {32 @ Override33 protected void initChannel (SocketChannel arg0) throws Excepti On {34 arg0.pipeline (). addLast (new TimeServerHandler (); 35} 36} 37 38 public static void main (String [] args) throws Exception {39 int port = 8080; 40 if (args! = Null & args. length> 0) {41 try {42 port = Integer. valueOf (args [0]); 43} 44 catch (NumberFormatException ex) {}45} 46 new TimeServer (). bind (port); 47} 48}
1 public class TimeServerHandler extends ChannelHandlerAdapter {2 // read/write operations for the network 3 @ Override 4 public void channelRead (ChannelHandlerContext ctx, Object msg) 5 throws Exception {6 ByteBuf buf = (ByteBuf) msg; 7 byte [] req = new byte [buf. readableBytes ()]; 8 buf. readBytes (req); 9 String body = new String (req, "UTF-8"); 10 System. out. println ("the time server order:" + body); 11 12 String currentTime = "QUER Y time order ". equalsIgnoreCase (body )? New Date (13 System. currentTimeMillis ()). toString (): "bad order"; 14 ByteBuf resp = Unpooled. copiedBuffer (currentTime. getBytes (); 15 ctx. write (resp); 16} 17 18 @ Override19 public void channelReadComplete (ChannelHandlerContext ctx) throws Exception {20 ctx. flush (); // It is used to write messages in the message sending queue to the SocketChannel and send them to the other party 21 // Netty's write method to prevent frequent wake-up Selector from sending messages, do not directly write the message into SocketChannel 22 // call the write method, just send the message to be sent to the buffer, and then call f Lush, write all the messages in the sending buffer 23 // to the SocketChannel. 24} 25 26 @ Override27 public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {28 ctx. close (); 29} 30}

 

/* TimeClient */

1 public class TimeClient {2 public void connect (String host, int port) throws Exception {3 // configure NIO thread group 4 EventLoopGroup group = new NioEventLoopGroup () on the server side (); 5 6 try {7 // Bootstrap class, which is an auxiliary startup class for starting the NIO Server 8 Bootstrap B = new Bootstrap (); 9 B. group (group ). channel (NioSocketChannel. class) 10. option (ChannelOption. TCP_NODELAY, true) 11. handler (new ChannelInitializer <SocketChannel> () {12 @ Override13 public voi D initChannel (SocketChannel ch) 14 throws Exception {15 ch. pipeline (). addLast (new TimeClientHandler (); 16} 17}); 18 19 // initiate asynchronous connection operation 20 ChannelFuture f = B. connect (host, port ). sync (); 21 22 // wait for the end link to close 23 f. channel (). closeFuture (). sync (); 24} finally {25 group. shutdownGracefully (); 26} 27} 28 29 public static void main (String [] args) throws Exception {30 int port = 8080; 31 if (args! = Null & args. length> 0) {32 try {33 port = Integer. valueOf (args [0]); 34} 35 catch (NumberFormatException ex) {} 36} 37 new TimeClient (). connect ("127.0.0.1", port); 38} 39}
1 public class TimeClientHandler extends ChannelHandlerAdapter {2 3 // write log 4 private static final Logger logger = 5 Logger. getLogger (TimeClientHandler. class. getName (); 6 7 private final ByteBuf firstMessage; 8 9 public TimeClientHandler () {10 byte [] req = "query time order ". getBytes (); 11 firstMessage = Unpooled. buffer (req. length); 12 firstMessage. writeBytes (req); 13} 14 15 @ Override16 public void cha NnelRead (ChannelHandlerContext ctx, Object msg) 17 throws Exception {18 ByteBuf buf = (ByteBuf) msg; 19 byte [] req = new byte [buf. readableBytes ()]; 20 buf. readBytes (req); 21 String body = new String (req, "UTF-8"); 22 System. out. println ("Now is:" + body); 23} 24 25 @ Override26 public void channelActive (ChannelHandlerContext ctx) {27 // after a tcp connection is established between the client and the server, the Netty NIO thread calls channelActive28 // sends the query time instruction to the server. 29 // call the writeAndFlush method of ChannelHandlerContext to send the request message to the server 30 // when the server responds, The channelRead method is called 31 ctx. writeAndFlush (firstMessage); 32} 33 34 @ Override35 public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {36 logger. warning ("message from:" + cause. getMessage (); 37 ctx. close (); 38} 39}

 

In this example, the processing of reading half a packet is not considered. For function demonstration and testing, this example is okay. However, if performance or stress testing is performed, it will not work properly. In the next section, we will illustrate how to process half-packet messages correctly.

In the source code src/main/java/Netty/, the project is divided into client and server.

Source code download: GitHub address: https://github.com/orange1438/Netty_Course

Digress: Although the article is purely written by my hand and does not have any copies, most of the content in the article comes from Netty's authoritative guide. I also learned it by the way. I previously worked on the C ++ server. As a result of the interview with C ++, the company's system was actually java, and the Chongqing, where I was not patient, had a poor C ++ performance, so I only learned java in my company. Of course, it is quite simple to learn about netty, for example, epoll, select, event-driven, and TCP/IP.

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.