Netty-based time server program code

Source: Internet
Author: User

[TOC]

Netty-based time server program code

The program code comes from chapter three of the Netty authoritative guide, but I have added comments, so it looks like it will be very well understood. It is important to note that the Timeserverhandler class in the Netty authoritative guide inherits Channelhandleradapter because it uses the Netty 5.x version, which is now officially obsolete, and I use Netty 4.x , so if inherit Channelhandleradapter, start the program without error, but do not work, that is, handler does not take effect this particular need to pay attention to.

Service-side code

Timeserver.java:

Package Cn.xpleaf.netty;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;public class Timeserver {/** * bind port number, start Netty service side * @param PO RT * @throws Exception */public void bind (int port) throws Exception {//Nioeventloopgroup is a thread group that contains a set of  NiO thread, dedicated to the processing of network events//actually they are reactor thread groups, about reactor, this is a design model,//reactor model is to put the message into a queue, through the asynchronous thread pool to consume/ In Netty, Nioeventloopgroup is Reactor,channelhandler is reactor model handler//can refer to the article: http://www.ivaneye.com/2016/07 /23/iomodel.html//Create two thread groups here, one for the server to accept the client connection, one for the Socketchannel network read and write Eventloopgroup bossgroup = new Nioev        Entloopgroup (); Eventloopgroup Workergroup = new NIOEVENTLOOPGROUP ();            try {//Create a secondary startup class on the NIO service side to reduce the development complexity of the server serverbootstrap B = new Serverbootstrap (); Pass two NIO thread groups as parameters to Serverbootstrap b.group (Bossgroup, Workergroup)//Nioserversocketchannel Correspondence J Serversocketchannel. Channel (Nioserversocketchannel.class)//settings Nioserversocketcha in the DK NiO class library The TCP parameter of the Nnel. Option (Channeloption.so_backlog, 1024)//Bind the processing class childchannelhandler of the I/O event, which acts like The handler class in reactor mode//is primarily used to handle network I/O events such as logging, decoding messages, and so on. Childhandler (New Childchannelhandler (            ));            Bind port, the synchronization waits successfully, the method is synchronous blocking, the binding succeeds and returns a channelfuture channelfuture f = b.bind (port). sync ();        Wait for the service-side listener port to close, block, wait for the service-side link to close after the main function exits F.channel (). Closefuture (). sync ();            } finally {//gracefully exits, releasing thread pool resource bossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }}/** * Implement Initchannel PartyWhen the Nioserversocketchannel is successfully created, the * is initialized by setting its channelhandler to channelpipeline for handling network I/O events * @author Yeyongha        O * * */Private class Childchannelhandler extends Channelinitializer<socketchannel> {@Override protected void Initchannel (Socketchannel ch) throws Exception {Ch.pipeline (). AddLast (New Timeserverhandler        ());        }} public static void Main (string[] args) throws Exception {int port = 8080;            if (args! = null && args.length > 0) {try {port = integer.valueof (port); } catch (NumberFormatException e) {//Todo:handle exception}} new Timeserver (    ). bind (port); }}

Timeserverhandler.java:

Package Cn.xpleaf.netty;import Java.sql.date;import Io.netty.buffer.bytebuf;import io.netty.buffer.unpooled;import Io.netty.channel.channelhandleradapter;import Io.netty.channel.channelhandlercontext;import io.netty.channel.channelinboundhandleradapter;/** * Note here that the authoritative guide to Netty The Timeserverhandler class inherits Channelhandleradapter, * because it uses the Netty 5.x version, which is now officially obsolete, and I use Netty 4.x, * So if inherit Channelhandleradapter, start the program without error, but do not work properly, that is, handler does not take effect * This is especially important to note.     * @author Yeyonghao * */public class Timeserverhandler extends Channelinboundhandleradapter {/** * write to network events */@Override public void Channelread (Channelhandlercontext ctx, Object msg) throws Exception {//Netty in Byte        BUF is similar to Bytebuffer in the NIO class library, but more powerful bytebuf buf = (bytebuf) msg;        Create a byte array as large as buf byte[] req = new byte[buf.readablebytes ()];        Copy data from BUF to req buf.readbytes (req);        String BODY = new String (req, "utf-8"); System.out.println ("The time server receive order:" + body);                 String currenttime = "QUERY time ORDER". Equalsignorecase (body)?        New Date (System.currenttimemillis ()). ToString (): "Bad ORDER";        Create Bytebuf object Bytebuf resp = Unpooled.copiedbuffer (Currenttime.getbytes ());    Asynchronously sent to client Ctx.write (RESP) via the Write method of Channelhandlercontext; }/** * Operations done after the write operation */@Override public void Channelreadcomplete (Channelhandlercontext ctx) throws Excep    tion {//Ctx.write () simply puts the message into the send buffer array, and calls flush to write all messages in its send buffer to Socketchannel ctx.flush ();        }/** * Release resources */@Override public void Exceptioncaught (Channelhandlercontext ctx, throwable cause) {    Ctx.close (); }}
Client code

Timeclient.java:

Package Cn.xpleaf.netty;import Io.netty.bootstrap.bootstrap;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.niosocketchannel;public class Timeclient {public void connect (int port, String host) throw        s Exception {//Configure client NIO thread Group Eventloopgroup group = new Nioeventloopgroup ();            try {//client is Bootstrap, note that client Bootstrap can only pass in a NiO thread group Bootstrap b = new Bootstrap (); The client is Niosocketchannel B.group (group). Channel (niosocketchannel.class). Option (channeloption.tcp _nodelay, True)//is the same as the server, except that the anonymous inner class is used here. Handler (New Channelinitializer<socketchannel&gt ;() {@Override protected void Initchannel (Socketchannel ch) throws Exception {ch.pipeline (). AddLast (New Timeclienthandler ());            }                });            Initiates an asynchronous connection operation (Note that the server is bind and the client needs connect) Channelfuture F = b.connect (host, port). sync ();        Wait for the client link to close F.channel (). Closefuture (). sync ();        } finally {//gracefully exits, releasing the NIO thread Group group.shutdowngracefully ();        }} public static void Main (string[] args) throws Exception {int port = 8080;            if (args! = null && args.length > 0) {try {port = integer.valueof (port); } catch (NumberFormatException e) {//takes the default value}} new Timeclient (). Connect (Port, "    localhost "); }}

Timeclienthandler.java:

Package Cn.xpleaf.netty;import Java.util.logging.logger;import Io.netty.buffer.bytebuf;import Io.netty.buffer.unpooled;import Io.netty.channel.channelhandleradapter;import Io.netty.channel.channelhandlercontext;import io.netty.channel.channelinboundhandleradapter;/** * The methods and functions of this class are similar to the handler of the service side * @author Yeyonghao * */public class Timeclienthandler extends Channelinboundhandleradapter {PR    Ivate static final Logger Logger = Logger.getlogger (TimeServerHandler.class.getName ());    Private Bytebuf firstmessage;        /** * Initialize the data to be sent */public Timeclienthandler () {byte[] req = "QUERY time ORDER". GetBytes ();        Firstmessage = Unpooled.buffer (req.length);    Firstmessage.writebytes (req); /** * When the client and server TCP link is established successfully, the Netty NiO thread calls the Channelactive method */@Override public void channelactive (CHANNELH    Andlercontext ctx) {//Send request message to server Ctx.writeandflush (firstmessage); } @Override public void Channelread (Channelhandlercontext ctx, objecT msg) throws Exception {bytebuf buf = (bytebuf) msg;        byte[] req = new byte[buf.readablebytes ()];        Buf.readbytes (req);        String BODY = new String (req, "utf-8");    System.out.println ("Now is:" + body); } @Override public void Exceptioncaught (Channelhandlercontext ctx, Throwable cause) throws Exception {Logger        . Warning ("Unexpected exception from downstream:");    Ctx.close (); }}

Netty-based time server program code

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.