In the previous article, "Android Netty-based message push scheme string receiving and sending (iii)" we introduced Netty string passing, and we know that Netty's message delivery is flow-based, passed through Channelbuffer, So naturally, object also needs to be converted into Channelbuffer to pass. Fortunately, Netty itself has written such a conversion tool for us. Objectencoder and Objectdecoder, let's introduce a case.
1. We construct an object for transmission (JavaBean)
@SuppressWarnings ("Serial") public class Command implements Serializable { private String actionname; Public String Getactionname () { return actionname; } public void Setactionname (String actionname) { this.actionname = ActionName; }}
2. Let's look at the client code first
public class Objectclient {public static void main (String args[]) {Clientbootstrap bootstrap = new Clientbootstrap (New Nio Clientsocketchannelfactory (Executors.newcachedthreadpool (), Executors.newcachedthreadpool ())); Bootstrap.setpipelinefactory (New Channelpipelinefactory () {@Overridepublic channelpipeline getpipeline () throws Exception {return channels.pipeline (new Objectencoder (), New Objectclienthandler ());}); Bootstrap.connect (New Inetsocketaddress ("127.0.0.1", 8000));}} Class Objectclienthandler extends Simplechannelhandler {/** * is triggered when bound to the server, sending messages to the server. */@Overridepublic void channelconnected (Channelhandlercontext ctx, channelstateevent e) {//Send object information to the server SendObject ( E.getchannel ());} /** * Send Object * @param channel */private void SendObject (Channel channel) {Command command = new Command (); command.setact Ionname ("Hello action."); Channel.write (command);}}
3. Take a look at the service-side code
public class objectserver {public static void main (String args[]) {//Server service initiator Serverbootstrap bootstrap = new Serverbootstrap (New Ni Oserversocketchannelfactory (Executors.newcachedthreadpool (), Executors.newcachedthreadpool ()));// Sets a Class (Handler) bootstrap.setpipelinefactory (new Channelpipelinefactory () {@Overridepublic that handles client messages and various message events Channelpipeline Getpipeline () throws Exception {///encode and then process your own business return Channels.pipeline (New Objectdecoder ( Classresolvers.cachedisabled (This.getclass (). getClassLoader ())), New Objectserverhandler ());}); Bootstrap.bind (New inetsocketaddress (8000));}} Class Objectserverhandler extends Simplechannelhandler {/** * triggers when the message is received */@Overridepublic void messagereceived ( Channelhandlercontext CTX, Messageevent e) throws Exception {command command = (command) e.getmessage ();//Print See if we just passed it over. The System.out.println (Command.getactionname ());}}
Run the server first, run the client, and then print the following string in the console of the server
Hello action.
The delivery of Android Netty-based message push scheme objects (iv)