1. What is Netty?
Nature: A jar package from JBoss
Objective: To rapidly develop high-performance, high-reliability network server and client programs
Pros: Provides asynchronous, event-driven network application frameworks and tools
Popular saying: A so-so deal with the socket
2, Netty's asynchronous event-driven model mainly involves the following core concepts
Channel: Represents a tunnel associated with a socket
channelpipeline: Pipeline, a channel has a channelpipeline,channelpipeline maintains a processing chain (strictly speaking two: upstream, downstream), The processing chain consists of a number of channel processor Channelhandler, each of which is passed to the next channel processor in the chain to continue processing after each channelhandler is processed.
Channelhandler: Channel processor, the user can define their own processing handle to handle each request, or pre-processing before making a request, typically have a codec/decoder: decoder, encoder.
channelevent: An event that is the processing object of the entire model, which is processed sequentially along the channelpipeline processing chain when an event is generated or triggered. channelfuture: Asynchronous result, this is the key to asynchronous event processing, when an event is processed, it can be directly returned in the form of channelfuture, without being blocked in the current operation. The result of the final execution can be obtained by Channelfuture , in which the channelfuture is added to the listener listener, and listener is triggered when the operation is finally executed. We can predefine our business code in the callback function of listener.
Channelpipeline actually maintains two processing chains: upstream, downstream. Upstream generally handles read events from the channel, while downstream generally handles write events to the channel. It is important to note that these two processing chains are independent of each other and are passed to the last Channelhandler processing in the upstream chain and are no longer transferred to the downstream chain to continue processing.
At the end of the downstream chain there will be a channelsink processing, the user can customize the implementation of this channelsink, the system also has a default implementation, When the last Channelhandler in the downstream chain is processed, it is passed to the Channelsink for final processing.
3. Demo
3.1, Nettyserver.java
PackageCom.jacky.server;ImportJava.util.concurrent.TimeUnit;ImportOrg.apache.log4j.Logger;ImportIo.netty.bootstrap.ServerBootstrap;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelInitializer;Importio.netty.channel.ChannelOption;ImportIo.netty.channel.ChannelPipeline;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioServerSocketChannel;ImportIo.netty.handler.codec.LengthFieldBasedFrameDecoder;ImportIo.netty.handler.timeout.IdleStateHandler; Public classNettyserver {Private StaticLogger Logger = Logger.getlogger (nettyserver.class); Private intPort; PublicNettyserver (intPort) { This. Port =Port; Bind (); } Private voidbind () {Eventloopgroup boss=NewNioeventloopgroup (); Eventloopgroup worker=NewNioeventloopgroup (); Try{Serverbootstrap bootstrap=NewServerbootstrap (); Bootstrap.group (boss, worker); Bootstrap.channel (Nioserversocketchannel.class); Bootstrap.option (Channeloption.so_backlog,1024);//Number of connectionsBootstrap.option (Channeloption.tcp_nodelay,true);//no delay, message sent immediatelyBootstrap.childoption (Channeloption.so_keepalive,true);//Long ConnectionsBootstrap.childhandler (NewChannelinitializer<socketchannel>() {@Overrideprotected voidInitchannel (Socketchannel socketchannel)throwsException {channelpipeline P=Socketchannel.pipeline (); P.addlast (NewNettyserverhandler ()); } }); Channelfuture F=Bootstrap.bind (port). sync (); if(F.issuccess ()) {Logger.debug ("Start Netty service succeeded, port number:" + This. Port); } //Close ConnectionF.channel (). Closefuture (). sync (); } Catch(Exception e) {logger.error ("Start Netty Service exception, exception information:" +e.getmessage ()); E.printstacktrace (); } finally{boss.shutdowngracefully (); Worker.shutdowngracefully (); } } Public Static voidMain (string[] args)throwsinterruptedexception {nettyserver server=NewNettyserver (9999); }}
3.2, Nettyserverhandler.java
PackageCom.jacky.server;Importjava.io.UnsupportedEncodingException;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext; Public classNettyserverhandlerextendsChannelhandleradapter {@Override Public voidChannelread (channelhandlercontext context, Object msg) {bytebuf buf=(BYTEBUF) msg; String recieved=getMessage (BUF); System.out.println ("The server received the message:" +recieved); Try{Context.writeandflush (Getsendbytebuf ("APPLE")); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } } /** Get information from BYTEBUF use UTF-8 encoding to return*/ PrivateString getMessage (bytebuf buf) {byte[] con =New byte[Buf.readablebytes ()]; Buf.readbytes (con); Try { return NewString (Con, "UTF-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); return NULL; } } Privatebytebuf getsendbytebuf (String message)throwsunsupportedencodingexception {byte[] req = Message.getbytes ("UTF-8"); Bytebuf Pingmessage=Unpooled.buffer (); Pingmessage.writebytes (req); returnPingmessage; }}
3.3, Nettyclient.java
Packagecom.jacky.client;ImportJava.util.concurrent.TimeUnit;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;ImportIo.netty.handler.codec.LengthFieldBasedFrameDecoder;ImportIo.netty.handler.timeout.IdleStateHandler; Public classnettyclient {/** Server port number*/ Private intPort; /** Server IP*/ PrivateString host; PublicNettyclient (intPort, String host)throwsinterruptedexception { This. Port =Port; This. Host =host; Start (); } Private voidStart ()throwsinterruptedexception {eventloopgroup eventloopgroup=NewNioeventloopgroup (); Try{Bootstrap Bootstrap=NewBootstrap (); Bootstrap.channel (Niosocketchannel.class); Bootstrap.option (Channeloption.so_keepalive,true); Bootstrap.group (Eventloopgroup); Bootstrap.remoteaddress (host, Port); Bootstrap.handler (NewChannelinitializer<socketchannel>() {@Overrideprotected voidInitchannel (Socketchannel socketchannel)throwsException {socketchannel.pipeline (). AddLast (NewNettyclienthandler ()); } }); Channelfuture Future=Bootstrap.connect (host, port). sync (); if(Future.issuccess ()) {Socketchannel Socketchannel=(Socketchannel) Future.channel (); System.out.println ("----------------Connect server Success----------------"); } future.channel (). Closefuture (). sync (); } finally{eventloopgroup.shutdowngracefully (); } } Public Static voidMain (string[] args)throwsinterruptedexception {nettyclient client=NewNettyclient (9999, "localhost"); }}
3.4, Nettyclienthandler.java
Packagecom.jacky.client;Importjava.io.UnsupportedEncodingException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.concurrent.TimeUnit;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext; Public classNettyclienthandlerextendsChannelhandleradapter {PrivateBytebuf Firstmessage; @Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {byte[] data = "Server, give me an apple". GetBytes (); Firstmessage=Unpooled.buffer (); Firstmessage.writebytes (data); Ctx.writeandflush (Firstmessage); } @Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {bytebuf buf=(BYTEBUF) msg; String Rev=getMessage (BUF); System.out.println ("Client Receives server data:" +rev); } PrivateString getMessage (bytebuf buf) {byte[] con =New byte[Buf.readablebytes ()]; Buf.readbytes (con); Try { return NewString (Con, "UTF-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); return NULL; } }}
Netty5 Getting Started Tutorial 0