Examples of protobuf in Netty.

Source: Internet
Author: User
Tags jboss

The Netty provides two encoders (Protobufencoder,protobufvarint32lengthfieldprepender) for the Protobuf, Two decoders (Protobufvarint32framedecoder,protobufdecoder)
[note] The so-called encoding is to encode the data type used by the application into a binary byte stream transmitted over the network, and vice versa.
Look at an example of a Netty official online that uses protobuf:
Localtimeprotocol.proto file:
[Java] View Plain copy print? package org.jboss.netty.example.localtime;   option optimize_for = speed;    enum continent {     AFRICA = 0;     america  = 1;     ANTARCTICA = 2;     ARCTIC = 3;      ASIA = 4;     ATLANTIC = 5;      AUSTRALIA = 6;     EUROPE = 7;     indian  = 8;     MIDEAST = 9;     PACIFIC = 10;   }   message location {     required Continent  continent = 1;     required string city = 2;  }    message locations {     repeated location location = 1;  }   enum dayofweek {     SUNDAY =  1;     MONDAY = 2;     TUESDAY = 3;      WEDNESDAY = 4;     THURSDAY = 5;      FRIDAY = 6;     SATURDAY = 7;  }   Message  LocalTime {     required uint32 year = 1;      required uint32 month = 2;     required uint32  dayofmonth = 4;     required DayOfWeek dayOfWeek = 5;      required uint32 hour = 6;     required uint32  minute = 7;     required uint32 second = 8;   }   Message localtimes {     repeated LocalTime localTime = 1;   }  

Package org.jboss.netty.example.localtime;
Option optimize_for = SPEED;
Enum Continent {
  AFRICA = 0;
  AMERICA = 1;
  antarctica = 2;
  ARCTIC = 3;
  ASIA = 4;
  Atlantic = 5;
  AUSTRALIA = 6;
  EUROPE = 7;
  INDIAN = 8;
  Mideast = 9;
  PACIFIC = ten;
}
Message Location {
  Required continent continent = 1;
  Required String city = 2;
}
Message Locations {
  repeated Location Location = 1;
}
Enum DayOfWeek {
  SUNDAY = 1;
  MONDAY = 2;
  Tuesday = 3;
  Wednesday = 4;
  Thursday = 5;
  FRIDAY = 6;
  SATURDAY = 7;
}
Message localtime {
  required uint32 year = 1;
  Required UInt32 month = 2;
  Required UInt32 dayofmonth = 4;
  Required DayOfWeek DayOfWeek = 5;
  Required UInt32 hour = 6;
  Required UInt32 minute = 7;
  Required UInt32 second = 8;
}
Message Localtimes {
  repeated localtime localtime = 1;
}

Client:
[Java] View Plain copy print? public class localtimeclient {          public  Static void main (String[] args)  throws Exception {            // parse options.            String host =  "localhost";            int port = 8080;            Collection<String> cities = new ArrayList< String> () {     private static final long serialversionuid =  1L;     {             add ( "America/new_york");             add ("Asia/Seoul");             }           };            // set up.            clientbootstrap bootstrap = new  clientbootstrap (                    new nioclientsocketchannelfactory (                             executors.newcachedthreadpool (),                             Executors.newcachedthreadpool ());              //  configure the event pipeline factory.    &NBSP;&NBSP;&NBSP;&NBsp;    bootstrap.setpipelinefactory (New localtimeclientpipelinefactory ());               // make a new connection .            ChannelFuture connectFuture =                bootstrap.connect (new  Inetsocketaddress (Host, port));              //  wait until the connection is made successfully.            Channel channel =  Connectfuture.awaituninterruptibly () Getchannel ();               // get the handler instance to initiate the request.            localtimeclienthandler handler =                channel.getpipeline (). Get (Localtimeclienthandler.class);               // request and get the response.            List<String> response =  Handler.getlocaltimes (cities);           // Close  The connection.            channel.close () awaituninterruptibly ();               // shut down all thread  pools to exit.            bootstrap.releaseexternalresources ();              // Print the Response at last but not least.            Iterator<String> i1 =  Cities.iterator ();           iterator<string> i2  = response.iterator ();           while  ( I1.hasnext ())  {                System.out.format ("%28s: %s%n",  i1.next (),  i2.next ());            }       }  }  

public class Localtimeclient {public static void main (string[] args) throws Exception {//Parse options.
        String host = "localhost";
        int port = 8080;
  Collection<string> cities = new Arraylist<string> () {private static final long serialversionuid = 1L;
          {Add ("america/new_york");
         Add ("Asia/seoul");
        }
        };
        Set up.
                        Clientbootstrap bootstrap = new Clientbootstrap (New Nioclientsocketchannelfactory (

        Executors.newcachedthreadpool (), Executors.newcachedthreadpool ());
        Configure the event pipeline factory.

        Bootstrap.setpipelinefactory (New Localtimeclientpipelinefactory ());
        Make a new connection.

        Channelfuture connectfuture = bootstrap.connect (new inetsocketaddress (host, port));
        Wait until the connection is made successfully. Channel Channel = ConnectfuturE.awaituninterruptibly (). Getchannel ();
        Get the handler instance to initiate the request.

        Localtimeclienthandler handler = Channel.getpipeline (). get (Localtimeclienthandler.class);
        Request and get the response.
        list<string> response = handler.getlocaltimes (cities);
        Close the connection.

        Channel.close (). awaituninterruptibly ();
        Shut down all thread pools to exit.

        Bootstrap.releaseexternalresources ();
        Print the response at last but not least.
        iterator<string> i1 = Cities.iterator ();
        iterator<string> i2 = Response.iterator ();
        while (I1.hasnext ()) {System.out.format ("%28s:%s%n", I1.next (), I2.next ()); }
    }
}
[Java] View Plain copy print? public class localtimeclientpipelinefactory implements channelpipelinefactory {           public channelpipeline getpipeline ()  throws  exception {           channelpipeline p =  pipeline ();    //decoding with            p.addlast ( "Framedecoder",  new protobufvarint32framedecoder ());          The   //constructor passes the type to be decoded            p.addlast (" Protobufdecoder ",  new protobufdecoder (LocalTimeProtocol.LocalTimes.getDefaultInstance ());     //Coding            p.addlast ("Frameencoder",  New protobufvarint32lengthfieldprepender ());           P.addlast ("Protobufencoder",  new protobufencoder ());    //business logic             p.addlast ("Handler",  new localtimeclienthandler ());            return p;       }   }  
public class Localtimeclientpipelinefactory implements Channelpipelinefactory {public

    channelpipeline Getpipeline () throws Exception {
        Channelpipeline P = pipeline ();
 Decoding with
        p.addlast ("Framedecoder", New Protobufvarint32framedecoder ());
        The constructor passes the type
        p.addlast ("Protobufdecoder") to be decoded, the new Protobufdecoder ( LocalTimeProtocol.LocalTimes.getDefaultInstance ()));
 Coding with
        p.addlast ("Frameencoder", New Protobufvarint32lengthfieldprepender ());
        P.addlast ("Protobufencoder", New Protobufencoder ());
 Business logic with
        p.addlast ("handler", New Localtimeclienthandler ());
        return p;
    }
}


[Java] View Plain copy print? public class localtimeclienthandler extends simplechannelupstreamhandler {           private static final Logger logger =  Logger.getlogger (                LocalTimeClientHandler.class.getName ());          // Stateful  Properties        private volatile Channel channel;       //to store results returned by server        private final  Blockingqueue<localtimes> answer = new linkedblockingqueue<localtimes> ();           public list<string> getlocaltimes (Collection <string> cities)  {            Locations.builder buiLder = locations.newbuilder ();    //constructs locations objects transmitted to the server             for  (string c: cities)  {                string[] components = c.split ("/");               builder.addlocation ( Location.newbuilder () .                    setcontinent (continent.valueof (components[0].touppercase)) .                    setcity (Components[1]). Build ());           }               channel.write (Builder.build ());                localtimes localtimes;           boolean  interrupted = false;           for  (;;)  {               try {      //from the queue, which is the localtimes from the service end.                     Localtimes = answer.take ();                    break;                } catch  (interruptedexception e)  {                    interrupted = true;                } &nbsp         }               if  (interrupted)  {                thread.currentthread () interrupt ();            }              list<string> result  = new ArrayList<String> ();            for  (Localtime lt: localtimes.getlocaltimelist ())  {                result.add (                        new formatter (). Format (                                 "%4d-%02d-%02d %02d:%02d:%02d %s",                                 lt.getyear (),                                 lt.getmonth (),                                 lt.getdayofmonth (),                                 lt.gethour (),                    &nbSp;           lt.getminute (),                                 lt.getsecond (),                                 lt.getdayofweek (). Name ()). ToString ());            }              return result;        }           @Override        public void handleupstream (                channelhandlercontext ctx, channelevent e)  throws  Exception {           if  (e instanceof channelstateevent )  {               logger.info ( E.tostring ());           }            super.handleupstream (ctx, e);       }            @Override        public void  Channelopen (channelhandlercontext ctx, channelstateevent e)                 

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.