Go Netty Getting Started (the simplest Netty client/server program)

Source: Internet
Author: User
Tags throwable

NiO in Java is a basic technique for solving blocking IO problems, but the preparation of NIO is a high requirement for Java programmers. Then Netty is a sophisticated network IO programming framework for simplifying operations. Here is a brief introduction of a program, the code is "Netty in action" inside, but the inside of the example is a bit of a problem, anyway I did not run successfully, modified after success. Directly on the code:

First, the server writing

Server code, listening for connections

 1 package com.gerry.netty.server; 2 3 Import Io.netty.bootstrap.ServerBootstrap; 4 Import io.netty.channel.ChannelFuture; 5 Import Io.netty.channel.ChannelInitializer; 6 Import Io.netty.channel.EventLoopGroup; 7 Import Io.netty.channel.nio.NioEventLoopGroup; 8 Import Io.netty.channel.socket.SocketChannel; 9 Import io.netty.channel.socket.nio.nioserversocketchannel;10 One public class Echoserver {$ private final int port;1 3 public echoserver (int port) {This.port = port;16}17-public void Start () throws Exception { Eventloopgroup Group = new Nioeventloopgroup (); try {serverbootstrap sb = new Serverbo Otstrap (); Sb.group (group)//Binding thread pool (nioserversocketchannel.class)//specified using Cha Nnel24. LocalAddress (This.port)//binding listening port. Childhandler (New Channelinitializer&lt ; Socketchannel> () {//BIND client connection when trigger action @OveRride28 protected void Initchannel (Socketchannel ch) throws Exception {29 System.out.println ("Connected ...; Client: "+ ch.remoteaddress ()); Ch.pipeline (). AddLast (New Echoserverhandler ()); Client trigger Operation}32}); Channelfuture CF = Sb.bind ( ). sync (); The server asynchronously creates bindings System.out.println (Echoserver.class + "started and listen on" + Cf.channel (). localaddress ()); Cf.channel (). Closefuture (). sync ();     Close server Channel--finally {PNS group.shutdowngracefully (). sync ();//Release thread pool resource 38}39}40 41 public static void Main (string[] args) throws Exception {new Echoserver (65535). Start ();//Start 43}44}

Specific code to handle the client connection

 1 package com.gerry.netty.server; 2 3 Import io.netty.buffer.Unpooled; 4 Import Io.netty.channel.ChannelFutureListener; 5 Import Io.netty.channel.ChannelHandlerContext; 6 Import Io.netty.channel.ChannelInboundHandlerAdapter; 7 8 public class Echoserverhandler extends Channelinboundhandleradapter {9 @Override10 public void Channelread (C Hannelhandlercontext ctx, Object msg) throws Exception {one System.out.println ("Server channelread ...; Received: "+ msg"), Ctx.write (msg),}14 @Override16 public void Channelreadcomplete (Channelhandl Ercontext ctx) throws Exception {System.out.println ("Server Channelreadcomplete.."); 18//The first method: Write an empty buf and refresh the write area. Close the sock channel connection when finished. Ctx.writeandflush (Unpooled.empty_buffer). AddListener (Channelfuturelistener.close);//ctx.flush (); The second method: Close the channel connection on the client side, so that the two-Channelreadcomplete method is triggered. //ctx.flush (). Close (). sync (); The Third Kind: change to this kind of writing also can, but this writing, there is no first method of good. 22}23 24 @Override25 public void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {26 SYSTEM.OUT.PRINTLN ("Server occur exception:" + Cause.getmessage ()); Cause.printstacktrace (); Ctx.clos E (); Closes the connection where the exception occurred 29}30}

Second, the client writing

The specific connection code

 1 package com.gerry.netty.client; 2 3 Import Io.netty.bootstrap.Bootstrap; 4 Import io.netty.channel.ChannelFuture; 5 Import Io.netty.channel.ChannelInitializer; 6 Import Io.netty.channel.EventLoopGroup; 7 Import Io.netty.channel.nio.NioEventLoopGroup; 8 Import Io.netty.channel.socket.SocketChannel; 9 Import io.netty.channel.socket.nio.niosocketchannel;10 Import java.net.inetsocketaddress;12 public class Echoclient {+ Private final String host;15 private final int port;16-public echoclient () {( 0);}20 public echoclient (int port) {("localhost", port),}24. Public Echoclient (S Tring host, int port) {This.host = host;27 This.port = port;28}29 public void start () throw s Exception {eventloopgroup group = new Nioeventloopgroup (); try {Bootstrap b = new Bo Otstrap (); B.group (group)//Registration thread pool (niosocketchannel. Class)//use Niosocketchannel as the channel class for the connection. Remoteaddress (New Inetsocketaddress (This.host, This.po                                 RT)//BIND connection port and host information. Handler (new channelinitializer<socketchannel> () {//bind connection initializer 38 @Override39 protected void Initchannel (Socketchannel ch) throws E                                     xception {System.out.println ("connected ..."); 41             Ch.pipeline (). AddLast (New Echoclienthandler ()); 42}43}); 44 System.out.println ("created."); Channelfuture CF = B.connect (). sync (); Asynchronous Connection Server System.out.println ("Connected ..."); Connection completed by Cf.channel (). Closefuture (). sync (); Asynchronously waits to close the connection channel50 System.out.println ("closed."); Close Finish} finally {group.shutdowngracefully (). sync ();//Release thread pool resource 53}54    }55-public static void main (string[] args) throws Exception {new echoclient ("127.0.0.1", 65535). Star T (); Connect 127.0.0.1/65535, and start 58}59}

After the connection is successful, the specific communication code

 1 package com.gerry.netty.client; 2 3 Import Java.nio.charset.Charset; 4 5 Import Io.netty.buffer.ByteBuf; 6 Import Io.netty.buffer.ByteBufUtil; 7 Import io.netty.buffer.Unpooled; 8 Import Io.netty.channel.ChannelHandlerContext; 9 Import io.netty.channel.simplechannelinboundhandler;10 Import io.netty.util.charsetutil;11 public class Echoclienthandler extends simplechannelinboundhandler<bytebuf> {@Override15 public void channelactive ( Channelhandlercontext ctx) throws Exception {System.out.println ("client channelactive.."); Ctx.writeandflush (Unpooled.copiedbuffer ("Netty rocks!", charsetutil.utf_8));         Must have flush18 19//must exist FLUSH20//Ctx.write (Unpooled.copiedbuffer ("Netty rocks!", Charsetutil.utf_8)); 21 Ctx.flush ();}23 @Override25 protected void channelRead0 (Channelhandlercontext ctx, Bytebuf ms g) throws Exception {System.out.println ("client channelread.."); Bytebuf buf = Msg.Readbytes (Msg.readablebytes ()); System.out.println ("Client Received:" + bytebufutil.hexdump (BUF) + ";     The value is: "+ buf.tostring (charset.forname (" Utf-8 "));//ctx.channel (). Close (). sync ();//client close channel Connection 30 }31 @Override33 public void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {3 4 Cause.printstacktrace (); Ctx.close (); 36}37 38}

Iii. Results

Run server first, and then run the client.

Reprint Link: http://www.cnblogs.com/liuming1992/p/4758532.html

Version used by Netty above

<!--Https://mvnrepository.com/artifact/io.netty/netty-all--
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
</dependency>

Go Netty Getting Started (the simplest Netty client/server 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.