Netty Study Notes (i)
Netty is a high-performance nio framework, and the use of Netty is simpler than writing large amounts of code compared to IO programming. Netty's main function is to be responsible for network transmission, Dubbo,rocket MQ and Elasticsearch use Netty as the network transmission Framework.
Netty features (the following features are from baidu, but I feel that the main use of developers when it is relatively simple ... )
1. design
Unified interface for multiple transport types-blocking and non-blocking
Simple but more powerful threading model
True non-connected Datagram Socket support
Link Logic support multiplexing
2. Ease of Use
A large number of Javadoc and code examples
In addition to the JDK 1.6 + additional Restrictions. (some features are supported only in Java 1.7 +.) Optional features may have additional restrictions. )
3. Performance
Better throughput than core Java apis, low Latency
Less resource consumption, thanks to shared pools and reuse
Reduce memory Copy
4. Robustness
Eliminate outofmemoryerror caused by slow, fast, or overloaded connections
Eliminate the unfair read/write ratios that are often found in NIO applications in high-speed networks
5. Security
Complete SSL/TLS and StartTLS support
Line in a restricted environment such as an Applet or OSGI
6. Community
Released earlier and more frequently
Community driven
Service Side:
Public class server {public static void main (string[] args) throws Exception{//1 Create a line two-pass group //one is for processing server-side receive client Connections//one is for network communication (network Read-write) eventloopgroup pgroup = new nioeventloopgroup (); Eventloopgroup cgroup = new nioeventloopgroup ();//2 Create the Accessibility class, A series of configurations for the server channel Serverbootstrap b = new serverbootstrap (); b.group (pgroup, cgroup)// Bind two thread groups .channel (nioserversocketchannel.class)//specify Nio's pattern .option (channeloption.so_backlog, 1024 )//set the TCP buffer //set log .handler (new logginghandler (loglevel.info)) .childhandler (new channelinitializer<socketchannel> () {protected void initchannel (SocketChannel sc) throws exception {sc.pipeline (). addlast (marshallingcodecfactory.buildmarshallingdecoder ()); Sc.pipeline (). addlast (marshallingcodecfactory.buildmarshallingencoder ());//the client and the server do not have any communication within 3s to close the response channel Conserve server resources (configuration is required on the client Side) SC.Pipeline (). addlast (new readtimeouthandler (3)); //3 here configures the handling of the specific data receive method Sc.pipeline (). addlast (new serverhandler ());}); /4 to bind channelfuture cf1 = b.bind (8765). sync ();//channelfuture cf2 = B.bind (8766). sync ();//5 wait to close Cf1.channel (). closefuture (). sync ();//cf2.channel (). closefuture (). sync (); pgroup.shutdowngracefully (); cgroup.shutdowngracefully ();}} Public class serverhandler extends channelhandleradapter{@Overridepublic void Channelactive (channelhandlercontext ctx) throws exception {} @Overridepublic void channelread (channelhandlercontext ctx, object msg) throws exception { request request = (request) msg; System.out.println ("server : " + request.getid () + ", " + Request.getname () + ", " + request.getrequestmessage ()); response response = new Response (); response.setid (request.getid ()); response.setname ("Response" + request.getid ()); Response.setresponsemessage ("response content" + request.getid ()); ctx.writeandflush (response);//.addlistener ( channelfuturelistener.close); Disconnect the channel Short link mode after the listener response is successful} @Overridepublic void channelreadcomplete ( Channelhandlercontext ctx) throws exception {} @Overridepublic void Exceptioncaught (channelhandlercontext ctx, throwable cause) throws exception { Ctx.close ();}}
Client:
public class client {private static class singletonholder {static Final client instance = new client ();} Public static client getinstance () {return singletonholder.instance;} private eventloopgroup group;private bootstrap b;private channelfuture cf ; Private client () {group = new nioeventloopgroup (); b = new bootstrap (); B.group (group) .channel (niosocketchannel.class) .handler (new logginghandler (LogLevel.INFO)) .handler (new channelinitializer<socketchannel> () {@Overrideprotected void Initchannel (socketchannel sc) throws exception { // Encode and decode Sc.pipeline (). addlast (marshallingcodecfactory.buildmarshallingdecoder ()) via JBoss marshalling; sc.pipeline ( ). addlast (marshallingcodecfactory.buildmarshallingencoder ());//the client and the server do not have any communication within 3s to close the response channel Save Server resources Sc.pipeline (). addlast (new readtimeouthandler (3)); //sc.pipeline (). addlast (new clienthandler ());} });} Public void connect () {try {this.cf = b.connect ("127.0.0.1", 8765). sync (); SYSTEM.OUT.PRINTLN ("the remote server is already connected, can be exchanged for data."); catch (exception e) {e.printstacktrace ();}} Public channelfuture getchannelfuture () {if (this.cf == null) {this.connect ();} If (!this.cf.channel (). isActive ()) {this.connect ();} return this.cf;} Public static void main (string[] args) throws exception{final client c = client.getinstance ();//c.connect (); Channelfuture cf = c.getchannelfuture (); for (int i = 1; i <= 3; i++ ) {request request = new request (); Request.setid ("" + i); Request.setname ("pro" + i); request.setrequestmessage ("data information" + i); cf.channel (). Writeandflush (request);TimeUnit.SECONDS.sleep (4);} Cf.channel (). closefuture (). sync ()//reconnect the server side new thread (new runnable () {@ with new one thread Overridepublic void run () {try {system.out.println ("enter sub-thread ..."); Channelfuture cf = c.getchannelfuture (); System.out.println (cf.channel (). isActive ()); System.out.println (cf.channel (). isOpen ());//send data again request request = new request (); Request.setid (" + 4"); request.setname ("pro" + 4); request.setrequestmessage ("data information" + 4); cf.channel (). writeandflush (request); cf.channel (). closefuture (). sync (); System.out.println ("child Thread ends."); catch (interruptedexception e) {e.printstacktrace ();}}). Start (); System.out.println ("disconnected, Main thread end:");}} Public class clienthandler extends channelhandleradapter{@Overridepublic void Channelactive (channelhandlercontext ctx) throws exception {} @Overridepublic void channelread (channelhandlercontext ctx, object msg) throws Exception {try {Response resp = ( Response) msg; System.out.println ("client : " + resp.getid () + ", " + Resp.getname () + ", " + resp.getresponsemessage ());} finally {referencecountutil.release (msg);}} @Overridepublic void channelreadcomplete (channelhandlercontext ctx) throws exception {} @Overridepublic void exceptioncaught (channelhandlercontext ctx, throwable Cause) throws exception {ctx.close ();}}
Marshalling factory:
public final class marshallingcodecfactory { /** * Create jboss marshalling Decoder marshallingdecoder * @return MarshallingDecoder */ public static Marshallingdecoder buildmarshallingdecoder () { // first, the marshalling instance object parameter serial identity is created by the marshalling tool Class's mastery method to create a Java sequence chemical plant Object. Final marshallerfactory marshallerfactory = marshalling.getprovidedmarshallerfactory (" Serial ");//created Marshallingconfiguration object, configured with version number 5 final marshallingconfiguration configuration = new marshallingconfiguration (); configuration.setversion (5);// Create providerunmarshallerprovider provider = new based on marshallerfactory and configuration Defaultunmarshallerprovider (marshallerfactory, configuration);//build Netty Marshallingdecoder object, The two parameters are provider and the maximum length after a single message is serialized, respectively MarshAllingdecoder decoder = new marshallingdecoder (provider, 1024);return decoder; } /** * Create jboss Marshalling encoder marshallingencoder * @return MarshallingEncoder */ public static MarshallingEncoder Buildmarshallingencoder () {final MarshallerFactory marshallerFactory = Marshalling.getprovidedmarshallerfactory ("serial"); final marshallingconfiguration configuration = new marshallingconfiguration (); configuration.setversion (5); Marshallerprovider provider = new defaultmarshallerprovider (marshallerFactory, Configuration),//build the Netty marshallingencoder object, marshallingencoder The Pojo object used to implement the serialized interface into a binary array marshallingencoder encoder = new marshallingencoder (provider); return encoder; }}
Netty Study Notes (i)