Network programming--The principle of RPC implementation--Directory
La La la
V2--netty-Pipeline.addlast (io.netty.handler.codec.messagetomessagecodec<inbound_in, OUTBOUND_IN>) Overwrite the encoding and decoding method.
Pipeline is equivalent to an interceptor. Add an implementation class for the Messagetomessagecodec interface in pipeline, the Encode () method in the implementation class of the interface to automatically convert the Sent object to Bytebuf,decode () Method automatically converts the received Bytebuf object to object
Class:server
Packagelime.pri.limeNio.netty.netty03;Importjava.net.InetSocketAddress;Importjava.util.Date;Importjava.util.List;ImportCom.alibaba.fastjson.JSON;Importcom.alibaba.fastjson.serializer.SerializerFeature;ImportIo.netty.bootstrap.ServerBootstrap;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelFutureListener;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInitializer;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.MessageToMessageCodec;ImportIo.netty.util.CharsetUtil;ImportLime.pri.limeNio.netty.netty03.entity.User; Public classServer { Public Static voidMain (string[] args)throwsException {serverbootstrap serverbootstrap=NewServerbootstrap (); Eventloopgroup boss=NewNioeventloopgroup (); Eventloopgroup worker=NewNioeventloopgroup (); Serverbootstrap.group (boss, worker); Serverbootstrap.channel (Nioserversocketchannel.class); Serverbootstrap.childhandler (NewChannelinitializer<socketchannel>() {@Overrideprotected voidInitchannel (Socketchannel ch)throwsException {Channelpipeline pipeline=Ch.pipeline (); Pipeline.addlast (NewMessagetomessagecodec<bytebuf, object>() {@Overrideprotected voidEncode (Channelhandlercontext ctx, Object msg, list<object> out)throwsException {System.out.println ("----Service-side encoding"); Out.add (Unpooled.buffer (). Writebytes (Json.tojsonstring (msg,serializerfeature.writeclassname). GetBytes ( (charsetutil.utf_8))); } @Overrideprotected voidDecode (Channelhandlercontext ctx, Bytebuf msg, list<object> out)throwsException {System.out.println ("----Service-side decoding"); Out.add (Json.parse (msg.tostring (Charsetutil.utf_8))); }}). AddLast (NewChannelhandleradapter () {@Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {System.out.println ("Client request data:" +msg); String Request=(String) msg; Object Response= "Request parameter is incorrect"; if("Query Date". Equalsignorecase (Request)) {Response= "Current system time:" +NewDate (). toString (); }Else if("Query User". Equalsignorecase (Request)) {Response=NewUser (1, "lime",NewDate ()); } channelfuture channelfuture=Ctx.writeandflush (response); Channelfuture.addlistener (channelfuturelistener.fire_exception_on_failure); Channelfuture.addlistener (channelfuturelistener.close_on_failure); Channelfuture.addlistener (Channelfuturelistener.close); } @Override Public voidExceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {cause.printstacktrace (); } }); } }); Channelfuture channelfuture= Serverbootstrap.bind (NewInetsocketaddress (9999) . sync (); Channelfuture.channel (). Closefuture (). sync (); Boss.close (); Worker.close (); }}
Class:client
Packagelime.pri.limeNio.netty.netty03;Importjava.net.InetSocketAddress;Importjava.util.List;ImportCom.alibaba.fastjson.JSON;Importcom.alibaba.fastjson.serializer.SerializerFeature;ImportIo.netty.bootstrap.Bootstrap;ImportIo.netty.buffer.ByteBuf;Importio.netty.buffer.Unpooled;Importio.netty.channel.ChannelFuture;ImportIo.netty.channel.ChannelFutureListener;ImportIo.netty.channel.ChannelHandlerAdapter;ImportIo.netty.channel.ChannelHandlerContext;ImportIo.netty.channel.ChannelInitializer;ImportIo.netty.channel.ChannelPipeline;ImportIo.netty.channel.EventLoopGroup;ImportIo.netty.channel.nio.NioEventLoopGroup;ImportIo.netty.channel.socket.SocketChannel;ImportIo.netty.channel.socket.nio.NioSocketChannel;ImportIo.netty.handler.codec.MessageToMessageCodec;ImportIo.netty.util.CharsetUtil; Public classClient { Public Static voidMain (string[] args)throwsException { for(inti = 0; I < 10; i++) { NewThread () {{Setdaemon (false); } Public voidrun () {Try{client (); } Catch(Exception e) {e.printstacktrace (); } }; }.start (); Thread.Sleep (1000); } } Private Static voidClient ()throwsException {Bootstrap Bootstrap=NewBootstrap (); Eventloopgroup worker=NewNioeventloopgroup (); Bootstrap.group (worker); Bootstrap.channel (Niosocketchannel.class); Bootstrap.handler (NewChannelinitializer<socketchannel>() {@Overrideprotected voidInitchannel (Socketchannel ch)throwsException {Channelpipeline pipeline=Ch.pipeline (); Pipeline.addlast (NewMessagetomessagecodec<bytebuf, object>() {@Overrideprotected voidEncode (Channelhandlercontext ctx, Object msg, list<object> out)throwsException {System.out.println ("----Client code"); Out.add (Unpooled.buffer (). Writebytes (Json.tojsonstring (msg, serializerfeature.writeclassname). GetBytes ( (charsetutil.utf_8))); } @Overrideprotected voidDecode (Channelhandlercontext ctx, Bytebuf msg, list<object> out)throwsException {System.out.println ("----Client decoding"); Out.add (Json.parse (msg.tostring (Charsetutil.utf_8))); }}). AddLast (NewChannelhandleradapter () {/*** Only network connection exceptions are caught by default*/@Override Public voidExceptioncaught (Channelhandlercontext ctx, throwable cause)throwsException {System.out.println (cause); } /*** The client sends a JSON-encoded BYTEBUF*/@Override Public voidChannelactive (Channelhandlercontext ctx)throwsException {String request=NULL; Switch((int) (Math.random () * 10)% 3) { Case0: Request= "Query Date"; Break; Case1: Request= "Query User"; Break; default: Request= "Query What?"; Break; } channelfuture channelfuture=Ctx.writeandflush (Request); Channelfuture.addlistener (channelfuturelistener.fire_exception_on_failure); Channelfuture.addlistener (channelfuturelistener.close_on_failure); } @Override Public voidChannelread (Channelhandlercontext ctx, Object msg)throwsException {System.out.println ("Server-side response data--" +msg); } }); } }); Channelfuture channelfuture; Channelfuture= Bootstrap.connect (NewInetsocketaddress (9999) . sync (); Channelfuture.channel (). Closefuture (). sync (); Worker.close (); }}
La La la
Network programming--The principle of RPC implementation--Netty--Iteration version V3--Encoding decoding