Java Network communication: Netty

Source: Internet
Author: User
Tags throwable

Tag: Message color ACE host 127.0.0.1 read off OID client

Netty provides asynchronous, event-driven network application frameworks and tools for rapid development of high-performance, high-reliability network servers and client programs.

In other words, Netty is a NIO-based client, a server-side programming framework that uses Netty to ensure that you quickly and simply develop a Web application, such as a client that implements some kind of protocol, a service-side application. Netty quite simplifies and streamlines the programming of Web applications, for example, the development of socket services for TCP and UDP.

This example uses Netty 5.0. On the code.

Service side:

ImportIo.netty.bootstrap.ServerBootstrap;Importio.netty.channel.ChannelFuture;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.nio.NioServerSocketChannel; Public classTimeserver { Public voidBindintPortthrowsException {//Configure the service-side NIO, cyclic event thread GroupEventloopgroup Bossgroup =NewNioeventloopgroup (); Eventloopgroup Workergroup=NewNioeventloopgroup (); Try{Serverbootstrap b=NewServerbootstrap ();//Configuration Class//Nioserversocketchannel as the channel class, its function corresponds to the serversocketchannel in the JDK NiO class libraryB.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Option (Channeloption.so_backlog,1024). Childhandler (NewTimeserverhandler ());//binding Event-handling classes//bind port, synchronization waits for successChannelfuture f =B.bind (port). sync (); //wait for the server to listen port shutdownF.channel (). Closefuture (). sync (); } finally {            //graceful exit, releasing thread pool resourcesbossgroup.shutdowngracefully ();        Workergroup.shutdowngracefully (); }    }     Public Static voidMain (string[] args)throwsException {intPort = 8080; if(Args! =NULL&& args.length > 0) {            Try{Port= Integer.valueof (args[0]); } Catch(NumberFormatException e) {//with default values            }        }        Newtimeserver (). bind (port); }}

Service-Side transaction processing class:

ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext; Public classTimeserverhandlerextendsChannelhandleradapter {/* when there is data, automatically called, read msg*/ Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {bytebuf buf=(BYTEBUF) msg; byte[] req =New byte[Buf.readablebytes ()];        Buf.readbytes (req); String Body=NewString (req, "UTF-8"); System.out.println ("The time server receive order:" +body); String currenttime= "QUERY time ORDER". Equalsignorecase (body)?Newjava.util.Date (System.currenttimemillis ()). ToString ():"Bad ORDER"; Bytebuf resp=Unpooled.copiedbuffer (Currenttime.getbytes ());    Ctx.write (RESP); }     Public voidChannelreadcomplete (Channelhandlercontext ctx)throwsException {ctx.flush (); }     Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause) {ctx.close (); }}

Client:

ImportIo.netty.bootstrap.Bootstrap;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelInitializer;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioSocketChannel; Public classtimeclient { Public voidConnectintPort, String host)throwsException {//Configuring client NiO thread GroupsEventloopgroup Group =NewNioeventloopgroup (); Try{Bootstrap b=NewBootstrap (); B.group (Group). Channel (Niosocketchannel.class). Option (Channeloption.tcp_nodelay,true). Handler (NewChannelinitializer<socketchannel>() {//channelinitializer<socketchannel> the anonymous class initializes the pipeline of the channel, adding the client transaction class to the queue @Override  Public voidinitchannel (socketchannel ch)throwsException {ch.pipeline (). AddLast (NewTimeclienthandler ());            }                    }); //initiating an asynchronous join operationChannelfuture f =B.connect (host, port). sync (); //Contemporary Client link shutdownF.channel (). Closefuture (). sync (); } finally {            //Graceful exit, free NIO thread groupgroup.shutdowngracefully (); }    }         Public Static voidMain (string[] args)throwsException {intPort = 8080; if(Args! =NULL&& args.length > 0) {        Try{Port= Integer.valueof (args[0]); } Catch(NumberFormatException e) {//with default values        }    }    NewTimeclient (). Connect (port, "127.0.0.1"); }}

Client Event Handling classes:

ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext;ImportJava.util.logging.Logger; Public classTimeclienthandlerextendsChannelhandleradapter {Private Static FinalLogger Logger =Logger. GetLogger (Timeclienthandler.class. GetName ()); Private FinalBytebuf Firstmessage;  PublicTimeclienthandler () {byte[] req = "QUERY time ORDER". GetBytes (); Firstmessage=Unpooled.buffer (req.length);    Firstmessage.writebytes (req); */* After successful connection, send message automatically * / Public voidchannelactive (Channelhandlercontext ctx) {Ctx.writeandflush (firstmessage); }/* When a message is returned, the function is called automatically read * / Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {bytebuf buf=(BYTEBUF) msg; byte[] req =New byte[Buf.readablebytes ()];        Buf.readbytes (req); String Body=NewString (req, "UTF-8"); System.out.println ("Now is:" +body); }/* Automatically called when an exception occurs * / Public voidexceptioncaught (Channelhandlercontext ctx, throwable cause) {//Freeing ResourcesLogger.warning ("Unexpected exception from downstream:" +cause.getmessage ());    Ctx.close (); }}

Java Network communication: Netty

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.