(十六)(中級篇)Protobuf編解碼(序列化)

 一,protobuf優點

 

 

 

假如你如今還在爲本身的技術擔心,假如你如今想提高本身的工資,假如你想在職場上得到更多的話語權,假如你想順利的度過35歲這個魔咒,假如你想體驗BAT的工做環境,那麼如今請咱們一塊兒開啓提高技術之旅吧,詳情請點擊http://106.12.206.16:8080/qingruihappy/index.html

 

 1:序列化後體積相比Json和XML很小,適合網絡傳輸
2:支持跨平臺多語言
3:消息格式升級和兼容性還不錯
4:序列化反序列化速度很快,快於Json的處理速速html

二,protobuf規則

這個不是重點,用到的時候能夠在網上查資料java

首先咱們來看一個簡單的序列化的例子,不牽涉到netty的bootstrap

UserModule緩存

 1 // Generated by the protocol buffer compiler. DO NOT EDIT!  2 // source: user.proto
 3 
 4 package bhz.netty.protobuf;  5 
 6 public final class UserModule {  7   private UserModule() {}  8   public static void registerAllExtensions(  9  com.google.protobuf.ExtensionRegistry registry) {  10  }  11   public interface UserOrBuilder  12  extends com.google.protobuf.MessageOrBuilder {  13 
 14     // required string userId = 1;
 15     /**  16  * <code>required string userId = 1;</code>  17      */
 18  boolean hasUserId();  19     /**  20  * <code>required string userId = 1;</code>  21      */
 22  java.lang.String getUserId();  23     /**  24  * <code>required string userId = 1;</code>  25      */
 26  com.google.protobuf.ByteString  27  getUserIdBytes();  28 
 29     // required int32 age = 2;
 30     /**  31  * <code>required int32 age = 2;</code>  32      */
 33  boolean hasAge();  34     /**  35  * <code>required int32 age = 2;</code>  36      */
 37     int getAge();  38 
 39     // required string userName = 3;
 40     /**  41  * <code>required string userName = 3;</code>  42      */
 43  boolean hasUserName();  44     /**  45  * <code>required string userName = 3;</code>  46      */
 47  java.lang.String getUserName();  48     /**  49  * <code>required string userName = 3;</code>  50      */
 51  com.google.protobuf.ByteString  52  getUserNameBytes();  53 
 54     // repeated string favorite = 4;
 55     /**  56  * <code>repeated string favorite = 4;</code>  57      */
 58     java.util.List<java.lang.String>
 59  getFavoriteList();  60     /**  61  * <code>repeated string favorite = 4;</code>  62      */
 63     int getFavoriteCount();  64     /**  65  * <code>repeated string favorite = 4;</code>  66      */
 67     java.lang.String getFavorite(int index);  68     /**  69  * <code>repeated string favorite = 4;</code>  70      */
 71  com.google.protobuf.ByteString  72         getFavoriteBytes(int index);  73  }  74   /**  75  * Protobuf type {@code User}  76    */
 77   public static final class User extends  78  com.google.protobuf.GeneratedMessage  79  implements UserOrBuilder {  80     // Use User.newBuilder() to construct.
 81     private User(com.google.protobuf.GeneratedMessage.Builder<?> builder) {  82  super(builder);  83       this.unknownFields = builder.getUnknownFields();  84  }  85     private User(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }  86 
 87     private static final User defaultInstance;  88     public static User getDefaultInstance() {  89       return defaultInstance;  90  }  91 
 92     public User getDefaultInstanceForType() {  93       return defaultInstance;  94  }  95 
 96     private final com.google.protobuf.UnknownFieldSet unknownFields;  97  @java.lang.Override  98     public final com.google.protobuf.UnknownFieldSet  99  getUnknownFields() {  100       return this.unknownFields;  101  }  102     private User(  103  com.google.protobuf.CodedInputStream input,  104  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  105  throws com.google.protobuf.InvalidProtocolBufferException {  106  initFields();  107       int mutable_bitField0_ = 0;  108       com.google.protobuf.UnknownFieldSet.Builder unknownFields =
 109  com.google.protobuf.UnknownFieldSet.newBuilder();  110       try {  111         boolean done = false;  112         while (!done) {  113           int tag = input.readTag();  114           switch (tag) {  115             case 0:  116               done = true;  117               break;  118             default: {  119               if (!parseUnknownField(input, unknownFields,  120  extensionRegistry, tag)) {  121                 done = true;  122  }  123               break;  124  }  125             case 10: {  126               bitField0_ |= 0x00000001;  127               userId_ = input.readBytes();  128               break;  129  }  130             case 16: {  131               bitField0_ |= 0x00000002;  132               age_ = input.readInt32();  133               break;  134  }  135             case 26: {  136               bitField0_ |= 0x00000004;  137               userName_ = input.readBytes();  138               break;  139  }  140             case 34: {  141               if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) {  142                 favorite_ = new com.google.protobuf.LazyStringArrayList();  143                 mutable_bitField0_ |= 0x00000008;  144  }  145  favorite_.add(input.readBytes());  146               break;  147  }  148  }  149  }  150       } catch (com.google.protobuf.InvalidProtocolBufferException e) {  151         throw e.setUnfinishedMessage(this);  152       } catch (java.io.IOException e) {  153         throw new com.google.protobuf.InvalidProtocolBufferException(  154             e.getMessage()).setUnfinishedMessage(this);  155       } finally {  156         if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) {  157           favorite_ = new com.google.protobuf.UnmodifiableLazyStringList(favorite_);  158  }  159         this.unknownFields = unknownFields.build();  160  makeExtensionsImmutable();  161  }  162  }  163     public static final com.google.protobuf.Descriptors.Descriptor  164  getDescriptor() {  165       return bhz.netty.protobuf.UserModule.internal_static_User_descriptor;  166  }  167 
 168     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable  169  internalGetFieldAccessorTable() {  170       return bhz.netty.protobuf.UserModule.internal_static_User_fieldAccessorTable  171  .ensureFieldAccessorsInitialized(  172               bhz.netty.protobuf.UserModule.User.class, bhz.netty.protobuf.UserModule.User.Builder.class);  173  }  174 
 175     public static com.google.protobuf.Parser<User> PARSER =
 176         new com.google.protobuf.AbstractParser<User>() {  177       public User parsePartialFrom(  178  com.google.protobuf.CodedInputStream input,  179  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  180  throws com.google.protobuf.InvalidProtocolBufferException {  181         return new User(input, extensionRegistry);  182  }  183  };  184 
 185  @java.lang.Override  186     public com.google.protobuf.Parser<User> getParserForType() {  187       return PARSER;  188  }  189 
 190     private int bitField0_;  191     // required string userId = 1;
 192     public static final int USERID_FIELD_NUMBER = 1;  193     private java.lang.Object userId_;  194     /**  195  * <code>required string userId = 1;</code>  196      */
 197     public boolean hasUserId() {  198       return ((bitField0_ & 0x00000001) == 0x00000001);  199  }  200     /**  201  * <code>required string userId = 1;</code>  202      */
 203     public java.lang.String getUserId() {  204       java.lang.Object ref = userId_;  205       if (ref instanceof java.lang.String) {  206         return (java.lang.String) ref;  207       } else {  208         com.google.protobuf.ByteString bs = 
 209             (com.google.protobuf.ByteString) ref;  210         java.lang.String s = bs.toStringUtf8();  211         if (bs.isValidUtf8()) {  212           userId_ = s;  213  }  214         return s;  215  }  216  }  217     /**  218  * <code>required string userId = 1;</code>  219      */
 220     public com.google.protobuf.ByteString  221  getUserIdBytes() {  222       java.lang.Object ref = userId_;  223       if (ref instanceof java.lang.String) {  224         com.google.protobuf.ByteString b = 
 225  com.google.protobuf.ByteString.copyFromUtf8(  226                 (java.lang.String) ref);  227         userId_ = b;  228         return b;  229       } else {  230         return (com.google.protobuf.ByteString) ref;  231  }  232  }  233 
 234     // required int32 age = 2;
 235     public static final int AGE_FIELD_NUMBER = 2;  236     private int age_;  237     /**  238  * <code>required int32 age = 2;</code>  239      */
 240     public boolean hasAge() {  241       return ((bitField0_ & 0x00000002) == 0x00000002);  242  }  243     /**  244  * <code>required int32 age = 2;</code>  245      */
 246     public int getAge() {  247       return age_;  248  }  249 
 250     // required string userName = 3;
 251     public static final int USERNAME_FIELD_NUMBER = 3;  252     private java.lang.Object userName_;  253     /**  254  * <code>required string userName = 3;</code>  255      */
 256     public boolean hasUserName() {  257       return ((bitField0_ & 0x00000004) == 0x00000004);  258  }  259     /**  260  * <code>required string userName = 3;</code>  261      */
 262     public java.lang.String getUserName() {  263       java.lang.Object ref = userName_;  264       if (ref instanceof java.lang.String) {  265         return (java.lang.String) ref;  266       } else {  267         com.google.protobuf.ByteString bs = 
 268             (com.google.protobuf.ByteString) ref;  269         java.lang.String s = bs.toStringUtf8();  270         if (bs.isValidUtf8()) {  271           userName_ = s;  272  }  273         return s;  274  }  275  }  276     /**  277  * <code>required string userName = 3;</code>  278      */
 279     public com.google.protobuf.ByteString  280  getUserNameBytes() {  281       java.lang.Object ref = userName_;  282       if (ref instanceof java.lang.String) {  283         com.google.protobuf.ByteString b = 
 284  com.google.protobuf.ByteString.copyFromUtf8(  285                 (java.lang.String) ref);  286         userName_ = b;  287         return b;  288       } else {  289         return (com.google.protobuf.ByteString) ref;  290  }  291  }  292 
 293     // repeated string favorite = 4;
 294     public static final int FAVORITE_FIELD_NUMBER = 4;  295     private com.google.protobuf.LazyStringList favorite_;  296     /**  297  * <code>repeated string favorite = 4;</code>  298      */
 299     public java.util.List<java.lang.String>
 300  getFavoriteList() {  301       return favorite_;  302  }  303     /**  304  * <code>repeated string favorite = 4;</code>  305      */
 306     public int getFavoriteCount() {  307       return favorite_.size();  308  }  309     /**  310  * <code>repeated string favorite = 4;</code>  311      */
 312     public java.lang.String getFavorite(int index) {  313       return favorite_.get(index);  314  }  315     /**  316  * <code>repeated string favorite = 4;</code>  317      */
 318     public com.google.protobuf.ByteString  319         getFavoriteBytes(int index) {  320       return favorite_.getByteString(index);  321  }  322 
 323     private void initFields() {  324       userId_ = "";  325       age_ = 0;  326       userName_ = "";  327       favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY;  328  }  329     private byte memoizedIsInitialized = -1;  330     public final boolean isInitialized() {  331       byte isInitialized = memoizedIsInitialized;  332       if (isInitialized != -1) return isInitialized == 1;  333 
 334       if (!hasUserId()) {  335         memoizedIsInitialized = 0;  336         return false;  337  }  338       if (!hasAge()) {  339         memoizedIsInitialized = 0;  340         return false;  341  }  342       if (!hasUserName()) {  343         memoizedIsInitialized = 0;  344         return false;  345  }  346       memoizedIsInitialized = 1;  347       return true;  348  }  349 
 350     public void writeTo(com.google.protobuf.CodedOutputStream output)  351  throws java.io.IOException {  352  getSerializedSize();  353       if (((bitField0_ & 0x00000001) == 0x00000001)) {  354         output.writeBytes(1, getUserIdBytes());  355  }  356       if (((bitField0_ & 0x00000002) == 0x00000002)) {  357         output.writeInt32(2, age_);  358  }  359       if (((bitField0_ & 0x00000004) == 0x00000004)) {  360         output.writeBytes(3, getUserNameBytes());  361  }  362       for (int i = 0; i < favorite_.size(); i++) {  363         output.writeBytes(4, favorite_.getByteString(i));  364  }  365  getUnknownFields().writeTo(output);  366  }  367 
 368     private int memoizedSerializedSize = -1;  369     public int getSerializedSize() {  370       int size = memoizedSerializedSize;  371       if (size != -1) return size;  372 
 373       size = 0;  374       if (((bitField0_ & 0x00000001) == 0x00000001)) {  375         size += com.google.protobuf.CodedOutputStream  376           .computeBytesSize(1, getUserIdBytes());  377  }  378       if (((bitField0_ & 0x00000002) == 0x00000002)) {  379         size += com.google.protobuf.CodedOutputStream  380           .computeInt32Size(2, age_);  381  }  382       if (((bitField0_ & 0x00000004) == 0x00000004)) {  383         size += com.google.protobuf.CodedOutputStream  384           .computeBytesSize(3, getUserNameBytes());  385  }  386  {  387         int dataSize = 0;  388         for (int i = 0; i < favorite_.size(); i++) {  389           dataSize += com.google.protobuf.CodedOutputStream  390  .computeBytesSizeNoTag(favorite_.getByteString(i));  391  }  392         size += dataSize;  393         size += 1 * getFavoriteList().size();  394  }  395       size += getUnknownFields().getSerializedSize();  396       memoizedSerializedSize = size;  397       return size;  398  }  399 
 400     private static final long serialVersionUID = 0L;  401  @java.lang.Override  402     protected java.lang.Object writeReplace()  403  throws java.io.ObjectStreamException {  404       return super.writeReplace();  405  }  406 
 407     public static bhz.netty.protobuf.UserModule.User parseFrom(  408  com.google.protobuf.ByteString data)  409  throws com.google.protobuf.InvalidProtocolBufferException {  410       return PARSER.parseFrom(data);  411  }  412     public static bhz.netty.protobuf.UserModule.User parseFrom(  413  com.google.protobuf.ByteString data,  414  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  415  throws com.google.protobuf.InvalidProtocolBufferException {  416       return PARSER.parseFrom(data, extensionRegistry);  417  }  418     public static bhz.netty.protobuf.UserModule.User parseFrom(byte[] data)  419  throws com.google.protobuf.InvalidProtocolBufferException {  420       return PARSER.parseFrom(data);  421  }  422     public static bhz.netty.protobuf.UserModule.User parseFrom(  423         byte[] data,  424  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  425  throws com.google.protobuf.InvalidProtocolBufferException {  426       return PARSER.parseFrom(data, extensionRegistry);  427  }  428     public static bhz.netty.protobuf.UserModule.User parseFrom(java.io.InputStream input)  429  throws java.io.IOException {  430       return PARSER.parseFrom(input);  431  }  432     public static bhz.netty.protobuf.UserModule.User parseFrom(  433  java.io.InputStream input,  434  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  435  throws java.io.IOException {  436       return PARSER.parseFrom(input, extensionRegistry);  437  }  438     public static bhz.netty.protobuf.UserModule.User parseDelimitedFrom(java.io.InputStream input)  439  throws java.io.IOException {  440       return PARSER.parseDelimitedFrom(input);  441  }  442     public static bhz.netty.protobuf.UserModule.User parseDelimitedFrom(  443  java.io.InputStream input,  444  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  445  throws java.io.IOException {  446       return PARSER.parseDelimitedFrom(input, extensionRegistry);  447  }  448     public static bhz.netty.protobuf.UserModule.User parseFrom(  449  com.google.protobuf.CodedInputStream input)  450  throws java.io.IOException {  451       return PARSER.parseFrom(input);  452  }  453     public static bhz.netty.protobuf.UserModule.User parseFrom(  454  com.google.protobuf.CodedInputStream input,  455  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  456  throws java.io.IOException {  457       return PARSER.parseFrom(input, extensionRegistry);  458  }  459 
 460     public static Builder newBuilder() { return Builder.create(); }  461     public Builder newBuilderForType() { return newBuilder(); }  462     public static Builder newBuilder(bhz.netty.protobuf.UserModule.User prototype) {  463       return newBuilder().mergeFrom(prototype);  464  }  465     public Builder toBuilder() { return newBuilder(this); }  466 
 467  @java.lang.Override  468     protected Builder newBuilderForType(  469  com.google.protobuf.GeneratedMessage.BuilderParent parent) {  470       Builder builder = new Builder(parent);  471       return builder;  472  }  473     /**  474  * Protobuf type {@code User}  475      */
 476     public static final class Builder extends  477         com.google.protobuf.GeneratedMessage.Builder<Builder>
 478  implements bhz.netty.protobuf.UserModule.UserOrBuilder {  479       public static final com.google.protobuf.Descriptors.Descriptor  480  getDescriptor() {  481         return bhz.netty.protobuf.UserModule.internal_static_User_descriptor;  482  }  483 
 484       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable  485  internalGetFieldAccessorTable() {  486         return bhz.netty.protobuf.UserModule.internal_static_User_fieldAccessorTable  487  .ensureFieldAccessorsInitialized(  488                 bhz.netty.protobuf.UserModule.User.class, bhz.netty.protobuf.UserModule.User.Builder.class);  489  }  490 
 491       // Construct using bhz.netty.protobuf.UserModule.User.newBuilder()
 492       private Builder() {  493  maybeForceBuilderInitialization();  494  }  495 
 496       private Builder(  497  com.google.protobuf.GeneratedMessage.BuilderParent parent) {  498  super(parent);  499  maybeForceBuilderInitialization();  500  }  501       private void maybeForceBuilderInitialization() {  502         if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {  503  }  504  }  505       private static Builder create() {  506         return new Builder();  507  }  508 
 509       public Builder clear() {  510  super.clear();  511         userId_ = "";  512         bitField0_ = (bitField0_ & ~0x00000001);  513         age_ = 0;  514         bitField0_ = (bitField0_ & ~0x00000002);  515         userName_ = "";  516         bitField0_ = (bitField0_ & ~0x00000004);  517         favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY;  518         bitField0_ = (bitField0_ & ~0x00000008);  519         return this;  520  }  521 
 522       public Builder clone() {  523         return create().mergeFrom(buildPartial());  524  }  525 
 526       public com.google.protobuf.Descriptors.Descriptor  527  getDescriptorForType() {  528         return bhz.netty.protobuf.UserModule.internal_static_User_descriptor;  529  }  530 
 531       public bhz.netty.protobuf.UserModule.User getDefaultInstanceForType() {  532         return bhz.netty.protobuf.UserModule.User.getDefaultInstance();  533  }  534 
 535       public bhz.netty.protobuf.UserModule.User build() {  536         bhz.netty.protobuf.UserModule.User result = buildPartial();  537         if (!result.isInitialized()) {  538           throw newUninitializedMessageException(result);  539  }  540         return result;  541  }  542 
 543       public bhz.netty.protobuf.UserModule.User buildPartial() {  544         bhz.netty.protobuf.UserModule.User result = new bhz.netty.protobuf.UserModule.User(this);  545         int from_bitField0_ = bitField0_;  546         int to_bitField0_ = 0;  547         if (((from_bitField0_ & 0x00000001) == 0x00000001)) {  548           to_bitField0_ |= 0x00000001;  549  }  550         result.userId_ = userId_;  551         if (((from_bitField0_ & 0x00000002) == 0x00000002)) {  552           to_bitField0_ |= 0x00000002;  553  }  554         result.age_ = age_;  555         if (((from_bitField0_ & 0x00000004) == 0x00000004)) {  556           to_bitField0_ |= 0x00000004;  557  }  558         result.userName_ = userName_;  559         if (((bitField0_ & 0x00000008) == 0x00000008)) {  560           favorite_ = new com.google.protobuf.UnmodifiableLazyStringList(  561  favorite_);  562           bitField0_ = (bitField0_ & ~0x00000008);  563  }  564         result.favorite_ = favorite_;  565         result.bitField0_ = to_bitField0_;  566  onBuilt();  567         return result;  568  }  569 
 570       public Builder mergeFrom(com.google.protobuf.Message other) {  571         if (other instanceof bhz.netty.protobuf.UserModule.User) {  572           return mergeFrom((bhz.netty.protobuf.UserModule.User)other);  573         } else {  574  super.mergeFrom(other);  575           return this;  576  }  577  }  578 
 579       public Builder mergeFrom(bhz.netty.protobuf.UserModule.User other) {  580         if (other == bhz.netty.protobuf.UserModule.User.getDefaultInstance()) return this;  581         if (other.hasUserId()) {  582           bitField0_ |= 0x00000001;  583           userId_ = other.userId_;  584  onChanged();  585  }  586         if (other.hasAge()) {  587  setAge(other.getAge());  588  }  589         if (other.hasUserName()) {  590           bitField0_ |= 0x00000004;  591           userName_ = other.userName_;  592  onChanged();  593  }  594         if (!other.favorite_.isEmpty()) {  595           if (favorite_.isEmpty()) {  596             favorite_ = other.favorite_;  597             bitField0_ = (bitField0_ & ~0x00000008);  598           } else {  599  ensureFavoriteIsMutable();  600  favorite_.addAll(other.favorite_);  601  }  602  onChanged();  603  }  604         this.mergeUnknownFields(other.getUnknownFields());  605         return this;  606  }  607 
 608       public final boolean isInitialized() {  609         if (!hasUserId()) {  610           
 611           return false;  612  }  613         if (!hasAge()) {  614           
 615           return false;  616  }  617         if (!hasUserName()) {  618           
 619           return false;  620  }  621         return true;  622  }  623 
 624       public Builder mergeFrom(  625  com.google.protobuf.CodedInputStream input,  626  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  627  throws java.io.IOException {  628         bhz.netty.protobuf.UserModule.User parsedMessage = null;  629         try {  630           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);  631         } catch (com.google.protobuf.InvalidProtocolBufferException e) {  632           parsedMessage = (bhz.netty.protobuf.UserModule.User) e.getUnfinishedMessage();  633           throw e;  634         } finally {  635           if (parsedMessage != null) {  636  mergeFrom(parsedMessage);  637  }  638  }  639         return this;  640  }  641       private int bitField0_;  642 
 643       // required string userId = 1;
 644       private java.lang.Object userId_ = "";  645       /**  646  * <code>required string userId = 1;</code>  647        */
 648       public boolean hasUserId() {  649         return ((bitField0_ & 0x00000001) == 0x00000001);  650  }  651       /**  652  * <code>required string userId = 1;</code>  653        */
 654       public java.lang.String getUserId() {  655         java.lang.Object ref = userId_;  656         if (!(ref instanceof java.lang.String)) {  657           java.lang.String s = ((com.google.protobuf.ByteString) ref)  658  .toStringUtf8();  659           userId_ = s;  660           return s;  661         } else {  662           return (java.lang.String) ref;  663  }  664  }  665       /**  666  * <code>required string userId = 1;</code>  667        */
 668       public com.google.protobuf.ByteString  669  getUserIdBytes() {  670         java.lang.Object ref = userId_;  671         if (ref instanceof String) {  672           com.google.protobuf.ByteString b = 
 673  com.google.protobuf.ByteString.copyFromUtf8(  674                   (java.lang.String) ref);  675           userId_ = b;  676           return b;  677         } else {  678           return (com.google.protobuf.ByteString) ref;  679  }  680  }  681       /**  682  * <code>required string userId = 1;</code>  683        */
 684       public Builder setUserId(  685  java.lang.String value) {  686         if (value == null) {  687     throw new NullPointerException();  688  }  689   bitField0_ |= 0x00000001;  690         userId_ = value;  691  onChanged();  692         return this;  693  }  694       /**  695  * <code>required string userId = 1;</code>  696        */
 697       public Builder clearUserId() {  698         bitField0_ = (bitField0_ & ~0x00000001);  699         userId_ = getDefaultInstance().getUserId();  700  onChanged();  701         return this;  702  }  703       /**  704  * <code>required string userId = 1;</code>  705        */
 706       public Builder setUserIdBytes(  707  com.google.protobuf.ByteString value) {  708         if (value == null) {  709     throw new NullPointerException();  710  }  711   bitField0_ |= 0x00000001;  712         userId_ = value;  713  onChanged();  714         return this;  715  }  716 
 717       // required int32 age = 2;
 718       private int age_ ;  719       /**  720  * <code>required int32 age = 2;</code>  721        */
 722       public boolean hasAge() {  723         return ((bitField0_ & 0x00000002) == 0x00000002);  724  }  725       /**  726  * <code>required int32 age = 2;</code>  727        */
 728       public int getAge() {  729         return age_;  730  }  731       /**  732  * <code>required int32 age = 2;</code>  733        */
 734       public Builder setAge(int value) {  735         bitField0_ |= 0x00000002;  736         age_ = value;  737  onChanged();  738         return this;  739  }  740       /**  741  * <code>required int32 age = 2;</code>  742        */
 743       public Builder clearAge() {  744         bitField0_ = (bitField0_ & ~0x00000002);  745         age_ = 0;  746  onChanged();  747         return this;  748  }  749 
 750       // required string userName = 3;
 751       private java.lang.Object userName_ = "";  752       /**  753  * <code>required string userName = 3;</code>  754        */
 755       public boolean hasUserName() {  756         return ((bitField0_ & 0x00000004) == 0x00000004);  757  }  758       /**  759  * <code>required string userName = 3;</code>  760        */
 761       public java.lang.String getUserName() {  762         java.lang.Object ref = userName_;  763         if (!(ref instanceof java.lang.String)) {  764           java.lang.String s = ((com.google.protobuf.ByteString) ref)  765  .toStringUtf8();  766           userName_ = s;  767           return s;  768         } else {  769           return (java.lang.String) ref;  770  }  771  }  772       /**  773  * <code>required string userName = 3;</code>  774        */
 775       public com.google.protobuf.ByteString  776  getUserNameBytes() {  777         java.lang.Object ref = userName_;  778         if (ref instanceof String) {  779           com.google.protobuf.ByteString b = 
 780  com.google.protobuf.ByteString.copyFromUtf8(  781                   (java.lang.String) ref);  782           userName_ = b;  783           return b;  784         } else {  785           return (com.google.protobuf.ByteString) ref;  786  }  787  }  788       /**  789  * <code>required string userName = 3;</code>  790        */
 791       public Builder setUserName(  792  java.lang.String value) {  793         if (value == null) {  794     throw new NullPointerException();  795  }  796   bitField0_ |= 0x00000004;  797         userName_ = value;  798  onChanged();  799         return this;  800  }  801       /**  802  * <code>required string userName = 3;</code>  803        */
 804       public Builder clearUserName() {  805         bitField0_ = (bitField0_ & ~0x00000004);  806         userName_ = getDefaultInstance().getUserName();  807  onChanged();  808         return this;  809  }  810       /**  811  * <code>required string userName = 3;</code>  812        */
 813       public Builder setUserNameBytes(  814  com.google.protobuf.ByteString value) {  815         if (value == null) {  816     throw new NullPointerException();  817  }  818   bitField0_ |= 0x00000004;  819         userName_ = value;  820  onChanged();  821         return this;  822  }  823 
 824       // repeated string favorite = 4;
 825       private com.google.protobuf.LazyStringList favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY;  826       private void ensureFavoriteIsMutable() {  827         if (!((bitField0_ & 0x00000008) == 0x00000008)) {  828           favorite_ = new com.google.protobuf.LazyStringArrayList(favorite_);  829           bitField0_ |= 0x00000008;  830  }  831  }  832       /**  833  * <code>repeated string favorite = 4;</code>  834        */
 835       public java.util.List<java.lang.String>
 836  getFavoriteList() {  837         return java.util.Collections.unmodifiableList(favorite_);  838  }  839       /**  840  * <code>repeated string favorite = 4;</code>  841        */
 842       public int getFavoriteCount() {  843         return favorite_.size();  844  }  845       /**  846  * <code>repeated string favorite = 4;</code>  847        */
 848       public java.lang.String getFavorite(int index) {  849         return favorite_.get(index);  850  }  851       /**  852  * <code>repeated string favorite = 4;</code>  853        */
 854       public com.google.protobuf.ByteString  855           getFavoriteBytes(int index) {  856         return favorite_.getByteString(index);  857  }  858       /**  859  * <code>repeated string favorite = 4;</code>  860        */
 861       public Builder setFavorite(  862           int index, java.lang.String value) {  863         if (value == null) {  864     throw new NullPointerException();  865  }  866  ensureFavoriteIsMutable();  867         favorite_.set(index, value);  868  onChanged();  869         return this;  870  }  871       /**  872  * <code>repeated string favorite = 4;</code>  873        */
 874       public Builder addFavorite(  875  java.lang.String value) {  876         if (value == null) {  877     throw new NullPointerException();  878  }  879  ensureFavoriteIsMutable();  880  favorite_.add(value);  881  onChanged();  882         return this;  883  }  884       /**  885  * <code>repeated string favorite = 4;</code>  886        */
 887       public Builder addAllFavorite(  888           java.lang.Iterable<java.lang.String> values) {  889  ensureFavoriteIsMutable();  890  super.addAll(values, favorite_);  891  onChanged();  892         return this;  893  }  894       /**  895  * <code>repeated string favorite = 4;</code>  896        */
 897       public Builder clearFavorite() {  898         favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY;  899         bitField0_ = (bitField0_ & ~0x00000008);  900  onChanged();  901         return this;  902  }  903       /**  904  * <code>repeated string favorite = 4;</code>  905        */
 906       public Builder addFavoriteBytes(  907  com.google.protobuf.ByteString value) {  908         if (value == null) {  909     throw new NullPointerException();  910  }  911  ensureFavoriteIsMutable();  912  favorite_.add(value);  913  onChanged();  914         return this;  915  }  916 
 917       // @@protoc_insertion_point(builder_scope:User)
 918  }  919 
 920     static {  921       defaultInstance = new User(true);  922  defaultInstance.initFields();  923  }  924 
 925     // @@protoc_insertion_point(class_scope:User)
 926  }  927 
 928   public interface GroupOrBuilder  929  extends com.google.protobuf.MessageOrBuilder {  930 
 931     // required int64 groupId = 1;
 932     /**  933  * <code>required int64 groupId = 1;</code>  934      */
 935  boolean hasGroupId();  936     /**  937  * <code>required int64 groupId = 1;</code>  938      */
 939     long getGroupId();  940 
 941     // required string groupName = 2;
 942     /**  943  * <code>required string groupName = 2;</code>  944      */
 945  boolean hasGroupName();  946     /**  947  * <code>required string groupName = 2;</code>  948      */
 949  java.lang.String getGroupName();  950     /**  951  * <code>required string groupName = 2;</code>  952      */
 953  com.google.protobuf.ByteString  954  getGroupNameBytes();  955  }  956   /**  957  * Protobuf type {@code Group}  958    */
 959   public static final class Group extends  960  com.google.protobuf.GeneratedMessage  961  implements GroupOrBuilder {  962     // Use Group.newBuilder() to construct.
 963     private Group(com.google.protobuf.GeneratedMessage.Builder<?> builder) {  964  super(builder);  965       this.unknownFields = builder.getUnknownFields();  966  }  967     private Group(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }  968 
 969     private static final Group defaultInstance;  970     public static Group getDefaultInstance() {  971       return defaultInstance;  972  }  973 
 974     public Group getDefaultInstanceForType() {  975       return defaultInstance;  976  }  977 
 978     private final com.google.protobuf.UnknownFieldSet unknownFields;  979  @java.lang.Override  980     public final com.google.protobuf.UnknownFieldSet  981  getUnknownFields() {  982       return this.unknownFields;  983  }  984     private Group(  985  com.google.protobuf.CodedInputStream input,  986  com.google.protobuf.ExtensionRegistryLite extensionRegistry)  987  throws com.google.protobuf.InvalidProtocolBufferException {  988  initFields();  989       int mutable_bitField0_ = 0;  990       com.google.protobuf.UnknownFieldSet.Builder unknownFields =
 991  com.google.protobuf.UnknownFieldSet.newBuilder();  992       try {  993         boolean done = false;  994         while (!done) {  995           int tag = input.readTag();  996           switch (tag) {  997             case 0:  998               done = true;  999               break; 1000             default: { 1001               if (!parseUnknownField(input, unknownFields, 1002  extensionRegistry, tag)) { 1003                 done = true; 1004  } 1005               break; 1006  } 1007             case 8: { 1008               bitField0_ |= 0x00000001; 1009               groupId_ = input.readInt64(); 1010               break; 1011  } 1012             case 18: { 1013               bitField0_ |= 0x00000002; 1014               groupName_ = input.readBytes(); 1015               break; 1016  } 1017  } 1018  } 1019       } catch (com.google.protobuf.InvalidProtocolBufferException e) { 1020         throw e.setUnfinishedMessage(this); 1021       } catch (java.io.IOException e) { 1022         throw new com.google.protobuf.InvalidProtocolBufferException( 1023             e.getMessage()).setUnfinishedMessage(this); 1024       } finally { 1025         this.unknownFields = unknownFields.build(); 1026  makeExtensionsImmutable(); 1027  } 1028  } 1029     public static final com.google.protobuf.Descriptors.Descriptor 1030  getDescriptor() { 1031       return bhz.netty.protobuf.UserModule.internal_static_Group_descriptor; 1032  } 1033 
1034     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable 1035  internalGetFieldAccessorTable() { 1036       return bhz.netty.protobuf.UserModule.internal_static_Group_fieldAccessorTable 1037  .ensureFieldAccessorsInitialized( 1038               bhz.netty.protobuf.UserModule.Group.class, bhz.netty.protobuf.UserModule.Group.Builder.class); 1039  } 1040 
1041     public static com.google.protobuf.Parser<Group> PARSER =
1042         new com.google.protobuf.AbstractParser<Group>() { 1043       public Group parsePartialFrom( 1044  com.google.protobuf.CodedInputStream input, 1045  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1046  throws com.google.protobuf.InvalidProtocolBufferException { 1047         return new Group(input, extensionRegistry); 1048  } 1049  }; 1050 
1051  @java.lang.Override 1052     public com.google.protobuf.Parser<Group> getParserForType() { 1053       return PARSER; 1054  } 1055 
1056     private int bitField0_; 1057     // required int64 groupId = 1;
1058     public static final int GROUPID_FIELD_NUMBER = 1; 1059     private long groupId_; 1060     /** 1061  * <code>required int64 groupId = 1;</code> 1062      */
1063     public boolean hasGroupId() { 1064       return ((bitField0_ & 0x00000001) == 0x00000001); 1065  } 1066     /** 1067  * <code>required int64 groupId = 1;</code> 1068      */
1069     public long getGroupId() { 1070       return groupId_; 1071  } 1072 
1073     // required string groupName = 2;
1074     public static final int GROUPNAME_FIELD_NUMBER = 2; 1075     private java.lang.Object groupName_; 1076     /** 1077  * <code>required string groupName = 2;</code> 1078      */
1079     public boolean hasGroupName() { 1080       return ((bitField0_ & 0x00000002) == 0x00000002); 1081  } 1082     /** 1083  * <code>required string groupName = 2;</code> 1084      */
1085     public java.lang.String getGroupName() { 1086       java.lang.Object ref = groupName_; 1087       if (ref instanceof java.lang.String) { 1088         return (java.lang.String) ref; 1089       } else { 1090         com.google.protobuf.ByteString bs = 
1091             (com.google.protobuf.ByteString) ref; 1092         java.lang.String s = bs.toStringUtf8(); 1093         if (bs.isValidUtf8()) { 1094           groupName_ = s; 1095  } 1096         return s; 1097  } 1098  } 1099     /** 1100  * <code>required string groupName = 2;</code> 1101      */
1102     public com.google.protobuf.ByteString 1103  getGroupNameBytes() { 1104       java.lang.Object ref = groupName_; 1105       if (ref instanceof java.lang.String) { 1106         com.google.protobuf.ByteString b = 
1107  com.google.protobuf.ByteString.copyFromUtf8( 1108                 (java.lang.String) ref); 1109         groupName_ = b; 1110         return b; 1111       } else { 1112         return (com.google.protobuf.ByteString) ref; 1113  } 1114  } 1115 
1116     private void initFields() { 1117       groupId_ = 0L; 1118       groupName_ = ""; 1119  } 1120     private byte memoizedIsInitialized = -1; 1121     public final boolean isInitialized() { 1122       byte isInitialized = memoizedIsInitialized; 1123       if (isInitialized != -1) return isInitialized == 1; 1124 
1125       if (!hasGroupId()) { 1126         memoizedIsInitialized = 0; 1127         return false; 1128  } 1129       if (!hasGroupName()) { 1130         memoizedIsInitialized = 0; 1131         return false; 1132  } 1133       memoizedIsInitialized = 1; 1134       return true; 1135  } 1136 
1137     public void writeTo(com.google.protobuf.CodedOutputStream output) 1138  throws java.io.IOException { 1139  getSerializedSize(); 1140       if (((bitField0_ & 0x00000001) == 0x00000001)) { 1141         output.writeInt64(1, groupId_); 1142  } 1143       if (((bitField0_ & 0x00000002) == 0x00000002)) { 1144         output.writeBytes(2, getGroupNameBytes()); 1145  } 1146  getUnknownFields().writeTo(output); 1147  } 1148 
1149     private int memoizedSerializedSize = -1; 1150     public int getSerializedSize() { 1151       int size = memoizedSerializedSize; 1152       if (size != -1) return size; 1153 
1154       size = 0; 1155       if (((bitField0_ & 0x00000001) == 0x00000001)) { 1156         size += com.google.protobuf.CodedOutputStream 1157           .computeInt64Size(1, groupId_); 1158  } 1159       if (((bitField0_ & 0x00000002) == 0x00000002)) { 1160         size += com.google.protobuf.CodedOutputStream 1161           .computeBytesSize(2, getGroupNameBytes()); 1162  } 1163       size += getUnknownFields().getSerializedSize(); 1164       memoizedSerializedSize = size; 1165       return size; 1166  } 1167 
1168     private static final long serialVersionUID = 0L; 1169  @java.lang.Override 1170     protected java.lang.Object writeReplace() 1171  throws java.io.ObjectStreamException { 1172       return super.writeReplace(); 1173  } 1174 
1175     public static bhz.netty.protobuf.UserModule.Group parseFrom( 1176  com.google.protobuf.ByteString data) 1177  throws com.google.protobuf.InvalidProtocolBufferException { 1178       return PARSER.parseFrom(data); 1179  } 1180     public static bhz.netty.protobuf.UserModule.Group parseFrom( 1181  com.google.protobuf.ByteString data, 1182  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1183  throws com.google.protobuf.InvalidProtocolBufferException { 1184       return PARSER.parseFrom(data, extensionRegistry); 1185  } 1186     public static bhz.netty.protobuf.UserModule.Group parseFrom(byte[] data) 1187  throws com.google.protobuf.InvalidProtocolBufferException { 1188       return PARSER.parseFrom(data); 1189  } 1190     public static bhz.netty.protobuf.UserModule.Group parseFrom( 1191         byte[] data, 1192  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1193  throws com.google.protobuf.InvalidProtocolBufferException { 1194       return PARSER.parseFrom(data, extensionRegistry); 1195  } 1196     public static bhz.netty.protobuf.UserModule.Group parseFrom(java.io.InputStream input) 1197  throws java.io.IOException { 1198       return PARSER.parseFrom(input); 1199  } 1200     public static bhz.netty.protobuf.UserModule.Group parseFrom( 1201  java.io.InputStream input, 1202  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1203  throws java.io.IOException { 1204       return PARSER.parseFrom(input, extensionRegistry); 1205  } 1206     public static bhz.netty.protobuf.UserModule.Group parseDelimitedFrom(java.io.InputStream input) 1207  throws java.io.IOException { 1208       return PARSER.parseDelimitedFrom(input); 1209  } 1210     public static bhz.netty.protobuf.UserModule.Group parseDelimitedFrom( 1211  java.io.InputStream input, 1212  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1213  throws java.io.IOException { 1214       return PARSER.parseDelimitedFrom(input, extensionRegistry); 1215  } 1216     public static bhz.netty.protobuf.UserModule.Group parseFrom( 1217  com.google.protobuf.CodedInputStream input) 1218  throws java.io.IOException { 1219       return PARSER.parseFrom(input); 1220  } 1221     public static bhz.netty.protobuf.UserModule.Group parseFrom( 1222  com.google.protobuf.CodedInputStream input, 1223  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1224  throws java.io.IOException { 1225       return PARSER.parseFrom(input, extensionRegistry); 1226  } 1227 
1228     public static Builder newBuilder() { return Builder.create(); } 1229     public Builder newBuilderForType() { return newBuilder(); } 1230     public static Builder newBuilder(bhz.netty.protobuf.UserModule.Group prototype) { 1231       return newBuilder().mergeFrom(prototype); 1232  } 1233     public Builder toBuilder() { return newBuilder(this); } 1234 
1235  @java.lang.Override 1236     protected Builder newBuilderForType( 1237  com.google.protobuf.GeneratedMessage.BuilderParent parent) { 1238       Builder builder = new Builder(parent); 1239       return builder; 1240  } 1241     /** 1242  * Protobuf type {@code Group} 1243      */
1244     public static final class Builder extends 1245         com.google.protobuf.GeneratedMessage.Builder<Builder>
1246  implements bhz.netty.protobuf.UserModule.GroupOrBuilder { 1247       public static final com.google.protobuf.Descriptors.Descriptor 1248  getDescriptor() { 1249         return bhz.netty.protobuf.UserModule.internal_static_Group_descriptor; 1250  } 1251 
1252       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable 1253  internalGetFieldAccessorTable() { 1254         return bhz.netty.protobuf.UserModule.internal_static_Group_fieldAccessorTable 1255  .ensureFieldAccessorsInitialized( 1256                 bhz.netty.protobuf.UserModule.Group.class, bhz.netty.protobuf.UserModule.Group.Builder.class); 1257  } 1258 
1259       // Construct using bhz.netty.protobuf.UserModule.Group.newBuilder()
1260       private Builder() { 1261  maybeForceBuilderInitialization(); 1262  } 1263 
1264       private Builder( 1265  com.google.protobuf.GeneratedMessage.BuilderParent parent) { 1266  super(parent); 1267  maybeForceBuilderInitialization(); 1268  } 1269       private void maybeForceBuilderInitialization() { 1270         if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { 1271  } 1272  } 1273       private static Builder create() { 1274         return new Builder(); 1275  } 1276 
1277       public Builder clear() { 1278  super.clear(); 1279         groupId_ = 0L; 1280         bitField0_ = (bitField0_ & ~0x00000001); 1281         groupName_ = ""; 1282         bitField0_ = (bitField0_ & ~0x00000002); 1283         return this; 1284  } 1285 
1286       public Builder clone() { 1287         return create().mergeFrom(buildPartial()); 1288  } 1289 
1290       public com.google.protobuf.Descriptors.Descriptor 1291  getDescriptorForType() { 1292         return bhz.netty.protobuf.UserModule.internal_static_Group_descriptor; 1293  } 1294 
1295       public bhz.netty.protobuf.UserModule.Group getDefaultInstanceForType() { 1296         return bhz.netty.protobuf.UserModule.Group.getDefaultInstance(); 1297  } 1298 
1299       public bhz.netty.protobuf.UserModule.Group build() { 1300         bhz.netty.protobuf.UserModule.Group result = buildPartial(); 1301         if (!result.isInitialized()) { 1302           throw newUninitializedMessageException(result); 1303  } 1304         return result; 1305  } 1306 
1307       public bhz.netty.protobuf.UserModule.Group buildPartial() { 1308         bhz.netty.protobuf.UserModule.Group result = new bhz.netty.protobuf.UserModule.Group(this); 1309         int from_bitField0_ = bitField0_; 1310         int to_bitField0_ = 0; 1311         if (((from_bitField0_ & 0x00000001) == 0x00000001)) { 1312           to_bitField0_ |= 0x00000001; 1313  } 1314         result.groupId_ = groupId_; 1315         if (((from_bitField0_ & 0x00000002) == 0x00000002)) { 1316           to_bitField0_ |= 0x00000002; 1317  } 1318         result.groupName_ = groupName_; 1319         result.bitField0_ = to_bitField0_; 1320  onBuilt(); 1321         return result; 1322  } 1323 
1324       public Builder mergeFrom(com.google.protobuf.Message other) { 1325         if (other instanceof bhz.netty.protobuf.UserModule.Group) { 1326           return mergeFrom((bhz.netty.protobuf.UserModule.Group)other); 1327         } else { 1328  super.mergeFrom(other); 1329           return this; 1330  } 1331  } 1332 
1333       public Builder mergeFrom(bhz.netty.protobuf.UserModule.Group other) { 1334         if (other == bhz.netty.protobuf.UserModule.Group.getDefaultInstance()) return this; 1335         if (other.hasGroupId()) { 1336  setGroupId(other.getGroupId()); 1337  } 1338         if (other.hasGroupName()) { 1339           bitField0_ |= 0x00000002; 1340           groupName_ = other.groupName_; 1341  onChanged(); 1342  } 1343         this.mergeUnknownFields(other.getUnknownFields()); 1344         return this; 1345  } 1346 
1347       public final boolean isInitialized() { 1348         if (!hasGroupId()) { 1349           
1350           return false; 1351  } 1352         if (!hasGroupName()) { 1353           
1354           return false; 1355  } 1356         return true; 1357  } 1358 
1359       public Builder mergeFrom( 1360  com.google.protobuf.CodedInputStream input, 1361  com.google.protobuf.ExtensionRegistryLite extensionRegistry) 1362  throws java.io.IOException { 1363         bhz.netty.protobuf.UserModule.Group parsedMessage = null; 1364         try { 1365           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); 1366         } catch (com.google.protobuf.InvalidProtocolBufferException e) { 1367           parsedMessage = (bhz.netty.protobuf.UserModule.Group) e.getUnfinishedMessage(); 1368           throw e; 1369         } finally { 1370           if (parsedMessage != null) { 1371  mergeFrom(parsedMessage); 1372  } 1373  } 1374         return this; 1375  } 1376       private int bitField0_; 1377 
1378       // required int64 groupId = 1;
1379       private long groupId_ ; 1380       /** 1381  * <code>required int64 groupId = 1;</code> 1382        */
1383       public boolean hasGroupId() { 1384         return ((bitField0_ & 0x00000001) == 0x00000001); 1385  } 1386       /** 1387  * <code>required int64 groupId = 1;</code> 1388        */
1389       public long getGroupId() { 1390         return groupId_; 1391  } 1392       /** 1393  * <code>required int64 groupId = 1;</code> 1394        */
1395       public Builder setGroupId(long value) { 1396         bitField0_ |= 0x00000001; 1397         groupId_ = value; 1398  onChanged(); 1399         return this; 1400  } 1401       /** 1402  * <code>required int64 groupId = 1;</code> 1403        */
1404       public Builder clearGroupId() { 1405         bitField0_ = (bitField0_ & ~0x00000001); 1406         groupId_ = 0L; 1407  onChanged(); 1408         return this; 1409  } 1410 
1411       // required string groupName = 2;
1412       private java.lang.Object groupName_ = ""; 1413       /** 1414  * <code>required string groupName = 2;</code> 1415        */
1416       public boolean hasGroupName() { 1417         return ((bitField0_ & 0x00000002) == 0x00000002); 1418  } 1419       /** 1420  * <code>required string groupName = 2;</code> 1421        */
1422       public java.lang.String getGroupName() { 1423         java.lang.Object ref = groupName_; 1424         if (!(ref instanceof java.lang.String)) { 1425           java.lang.String s = ((com.google.protobuf.ByteString) ref) 1426  .toStringUtf8(); 1427           groupName_ = s; 1428           return s; 1429         } else { 1430           return (java.lang.String) ref; 1431  } 1432  } 1433       /** 1434  * <code>required string groupName = 2;</code> 1435        */
1436       public com.google.protobuf.ByteString 1437  getGroupNameBytes() { 1438         java.lang.Object ref = groupName_; 1439         if (ref instanceof String) { 1440           com.google.protobuf.ByteString b = 
1441  com.google.protobuf.ByteString.copyFromUtf8( 1442                   (java.lang.String) ref); 1443           groupName_ = b; 1444           return b; 1445         } else { 1446           return (com.google.protobuf.ByteString) ref; 1447  } 1448  } 1449       /** 1450  * <code>required string groupName = 2;</code> 1451        */
1452       public Builder setGroupName( 1453  java.lang.String value) { 1454         if (value == null) { 1455     throw new NullPointerException(); 1456  } 1457   bitField0_ |= 0x00000002; 1458         groupName_ = value; 1459  onChanged(); 1460         return this; 1461  } 1462       /** 1463  * <code>required string groupName = 2;</code> 1464        */
1465       public Builder clearGroupName() { 1466         bitField0_ = (bitField0_ & ~0x00000002); 1467         groupName_ = getDefaultInstance().getGroupName(); 1468  onChanged(); 1469         return this; 1470  } 1471       /** 1472  * <code>required string groupName = 2;</code> 1473        */
1474       public Builder setGroupNameBytes( 1475  com.google.protobuf.ByteString value) { 1476         if (value == null) { 1477     throw new NullPointerException(); 1478  } 1479   bitField0_ |= 0x00000002; 1480         groupName_ = value; 1481  onChanged(); 1482         return this; 1483  } 1484 
1485       // @@protoc_insertion_point(builder_scope:Group)
1486  } 1487 
1488     static { 1489       defaultInstance = new Group(true); 1490  defaultInstance.initFields(); 1491  } 1492 
1493     // @@protoc_insertion_point(class_scope:Group)
1494  } 1495 
1496   private static com.google.protobuf.Descriptors.Descriptor 1497  internal_static_User_descriptor; 1498   private static
1499  com.google.protobuf.GeneratedMessage.FieldAccessorTable 1500  internal_static_User_fieldAccessorTable; 1501   private static com.google.protobuf.Descriptors.Descriptor 1502  internal_static_Group_descriptor; 1503   private static
1504  com.google.protobuf.GeneratedMessage.FieldAccessorTable 1505  internal_static_Group_fieldAccessorTable; 1506 
1507   public static com.google.protobuf.Descriptors.FileDescriptor 1508  getDescriptor() { 1509     return descriptor; 1510  } 1511   private static com.google.protobuf.Descriptors.FileDescriptor 1512  descriptor; 1513   static { 1514     java.lang.String[] descriptorData = { 1515       "\n\nuser.proto\"G\n\004User\022\016\n\006userId\030\001 \002(\t\022\013\n\003" +
1516       "age\030\002 \002(\005\022\020\n\010userName\030\003 \002(\t\022\020\n\010favorite\030" +
1517       "\004 \003(\t\"+\n\005Group\022\017\n\007groupId\030\001 \002(\003\022\021\n\tgroup" +
1518       "Name\030\002 \002(\tB \n\022bhz.netty.protobufB\nUserMo" +
1519       "dule"
1520  }; 1521     com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
1522       new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { 1523         public com.google.protobuf.ExtensionRegistry assignDescriptors( 1524  com.google.protobuf.Descriptors.FileDescriptor root) { 1525           descriptor = root; 1526           internal_static_User_descriptor =
1527             getDescriptor().getMessageTypes().get(0); 1528           internal_static_User_fieldAccessorTable = new
1529  com.google.protobuf.GeneratedMessage.FieldAccessorTable( 1530  internal_static_User_descriptor, 1531               new java.lang.String[] { "UserId", "Age", "UserName", "Favorite", }); 1532           internal_static_Group_descriptor =
1533             getDescriptor().getMessageTypes().get(1); 1534           internal_static_Group_fieldAccessorTable = new
1535  com.google.protobuf.GeneratedMessage.FieldAccessorTable( 1536  internal_static_Group_descriptor, 1537               new java.lang.String[] { "GroupId", "GroupName", }); 1538           return null; 1539  } 1540  }; 1541  com.google.protobuf.Descriptors.FileDescriptor 1542  .internalBuildGeneratedFileFrom(descriptorData, 1543         new com.google.protobuf.Descriptors.FileDescriptor[] { 1544  }, assigner); 1545  } 1546 
1547   // @@protoc_insertion_point(outer_class_scope)
1548 }
View Code

 

這個代碼是通過protobuf處理過的,不是手寫的代碼,他會被程序解讀的,不須要本身花費太多的精力來看的。服務器

首先咱們來看一下序列化網絡

 1     //1. 本身編寫了user.proto 數據傳輸格式 執行protoc.exe程序 生成對應的java代碼  2     
 3     //2. 咱們接下來對一個對象進行序列化和反序列化操做
 4     
 5     /**  6  * 序列化方法  7  * @return  8      */
 9     public static byte[] SerialObject2Bytes(){ 10         
11         int a = 5; 12         int b = 432343242; 13         
14         double c = 0.1;        // 15         
16         
17         Builder userBuilder = UserModule.User.newBuilder(); 18         //設置內容
19  userBuilder 20         .setUserId("1001") 21         .setAge(30) 22         .setUserName("張三") 23         .addFavorite("足球") 24         .addFavorite("籃球"); 25         //構造對象
26         User user = userBuilder.build(); 27         byte[] userBytes = user.toByteArray(); 28         return userBytes; 29         
30  } 31

 

 

1     public static void main(String[] args) { 2         
3         byte[] userBytes = SerialObject2Bytes(); 4  System.err.println(Arrays.toString(userBytes)); 5         
6     }

 

 

結果app

1 [10, 4, 49, 48, 48, 49, 16, 30, 26, 6, -27, -68, -96, -28, -72, -119, 34, 6, -24, -74, -77, -25, -112, -125, 34, 6, -25, -81, -82, -25, -112, -125]

 

反序列化socket

 1 /**  2  * 反序列化方法  3  * @param bytes  4  * @return  5      */
 6     public static User SerialBytes2Object(byte[] bytes){  7         try {  8             return UserModule.User.parseFrom(bytes);  9         } catch (InvalidProtocolBufferException e) { 10  e.printStackTrace(); 11  } 12         return null; 13     }
1 public static void main(String[] args) { 2         
3         byte[] userBytes = SerialObject2Bytes(); 4         
5         User user = SerialBytes2Object(userBytes); 6         System.err.println(user.getFavorite(0)); 7  System.err.println(user.getUserName()); 8         
9     }

 

結果:ide

足球
張三oop

三,protobuf在netty中的編解碼應用

3.1,build.bat

1 protoc ./proto/*.proto --java_out=./src 2 
3 pause,

3.2,request.proto

 1 option java_package = "bhz.netty.protobuf";  2 option java_outer_classname = "RequestModule";  3 
 4 message Request {  5     required string id = 1;  6     
 7     required int32 sequence = 2;  8     
 9     required string name = 3; 10     
11     repeated string favorite = 4; 12 }

 

3.3,RequestModule.java

// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto/request.proto
 package bhz.netty.protobuf; public final class RequestModule { private RequestModule() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface RequestOrBuilder extends com.google.protobuf.MessageOrBuilder { // required string id = 1;
    /** * <code>required string id = 1;</code> */ boolean hasId(); /** * <code>required string id = 1;</code> */ java.lang.String getId(); /** * <code>required string id = 1;</code> */ com.google.protobuf.ByteString getIdBytes(); // required int32 sequence = 2;
    /** * <code>required int32 sequence = 2;</code> */ boolean hasSequence(); /** * <code>required int32 sequence = 2;</code> */
    int getSequence(); // required string name = 3;
    /** * <code>required string name = 3;</code> */ boolean hasName(); /** * <code>required string name = 3;</code> */ java.lang.String getName(); /** * <code>required string name = 3;</code> */ com.google.protobuf.ByteString getNameBytes(); // repeated string favorite = 4;
    /** * <code>repeated string favorite = 4;</code> */ java.util.List<java.lang.String> getFavoriteList(); /** * <code>repeated string favorite = 4;</code> */
    int getFavoriteCount(); /** * <code>repeated string favorite = 4;</code> */ java.lang.String getFavorite(int index); /** * <code>repeated string favorite = 4;</code> */ com.google.protobuf.ByteString getFavoriteBytes(int index); } /** * Protobuf type {@code Request} */
  public static final class Request extends com.google.protobuf.GeneratedMessage implements RequestOrBuilder { // Use Request.newBuilder() to construct.
    private Request(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Request(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Request defaultInstance; public static Request getDefaultInstance() { return defaultInstance; } public Request getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Request( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; id_ = input.readBytes(); break; } case 16: { bitField0_ |= 0x00000002; sequence_ = input.readInt32(); break; } case 26: { bitField0_ |= 0x00000004; name_ = input.readBytes(); break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { favorite_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000008; } favorite_.add(input.readBytes()); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { favorite_ = new com.google.protobuf.UnmodifiableLazyStringList(favorite_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return bhz.netty.protobuf.RequestModule.internal_static_Request_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return bhz.netty.protobuf.RequestModule.internal_static_Request_fieldAccessorTable .ensureFieldAccessorsInitialized( bhz.netty.protobuf.RequestModule.Request.class, bhz.netty.protobuf.RequestModule.Request.Builder.class); } public static com.google.protobuf.Parser<Request> PARSER =
        new com.google.protobuf.AbstractParser<Request>() { public Request parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Request(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Request> getParserForType() { return PARSER; } private int bitField0_; // required string id = 1;
    public static final int ID_FIELD_NUMBER = 1; private java.lang.Object id_; /** * <code>required string id = 1;</code> */
    public boolean hasId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string id = 1;</code> */
    public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { id_ = s; } return s; } } /** * <code>required string id = 1;</code> */
    public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // required int32 sequence = 2;
    public static final int SEQUENCE_FIELD_NUMBER = 2; private int sequence_; /** * <code>required int32 sequence = 2;</code> */
    public boolean hasSequence() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required int32 sequence = 2;</code> */
    public int getSequence() { return sequence_; } // required string name = 3;
    public static final int NAME_FIELD_NUMBER = 3; private java.lang.Object name_; /** * <code>required string name = 3;</code> */
    public boolean hasName() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string name = 3;</code> */
    public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * <code>required string name = 3;</code> */
    public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // repeated string favorite = 4;
    public static final int FAVORITE_FIELD_NUMBER = 4; private com.google.protobuf.LazyStringList favorite_; /** * <code>repeated string favorite = 4;</code> */
    public java.util.List<java.lang.String> getFavoriteList() { return favorite_; } /** * <code>repeated string favorite = 4;</code> */
    public int getFavoriteCount() { return favorite_.size(); } /** * <code>repeated string favorite = 4;</code> */
    public java.lang.String getFavorite(int index) { return favorite_.get(index); } /** * <code>repeated string favorite = 4;</code> */
    public com.google.protobuf.ByteString getFavoriteBytes(int index) { return favorite_.getByteString(index); } private void initFields() { id_ = ""; sequence_ = 0; name_ = ""; favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasId()) { memoizedIsInitialized = 0; return false; } if (!hasSequence()) { memoizedIsInitialized = 0; return false; } if (!hasName()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getIdBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeInt32(2, sequence_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getNameBytes()); } for (int i = 0; i < favorite_.size(); i++) { output.writeBytes(4, favorite_.getByteString(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getIdBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, sequence_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getNameBytes()); } { int dataSize = 0; for (int i = 0; i < favorite_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(favorite_.getByteString(i)); } size += dataSize; size += 1 * getFavoriteList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static bhz.netty.protobuf.RequestModule.Request parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static bhz.netty.protobuf.RequestModule.Request parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static bhz.netty.protobuf.RequestModule.Request parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static bhz.netty.protobuf.RequestModule.Request parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static bhz.netty.protobuf.RequestModule.Request parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static bhz.netty.protobuf.RequestModule.Request parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static bhz.netty.protobuf.RequestModule.Request parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static bhz.netty.protobuf.RequestModule.Request parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static bhz.netty.protobuf.RequestModule.Request parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static bhz.netty.protobuf.RequestModule.Request parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(bhz.netty.protobuf.RequestModule.Request prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Request} */
    public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements bhz.netty.protobuf.RequestModule.RequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return bhz.netty.protobuf.RequestModule.internal_static_Request_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return bhz.netty.protobuf.RequestModule.internal_static_Request_fieldAccessorTable .ensureFieldAccessorsInitialized( bhz.netty.protobuf.RequestModule.Request.class, bhz.netty.protobuf.RequestModule.Request.Builder.class); } // Construct using bhz.netty.protobuf.RequestModule.Request.newBuilder()
      private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); id_ = ""; bitField0_ = (bitField0_ & ~0x00000001); sequence_ = 0; bitField0_ = (bitField0_ & ~0x00000002); name_ = ""; bitField0_ = (bitField0_ & ~0x00000004); favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return bhz.netty.protobuf.RequestModule.internal_static_Request_descriptor; } public bhz.netty.protobuf.RequestModule.Request getDefaultInstanceForType() { return bhz.netty.protobuf.RequestModule.Request.getDefaultInstance(); } public bhz.netty.protobuf.RequestModule.Request build() { bhz.netty.protobuf.RequestModule.Request result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public bhz.netty.protobuf.RequestModule.Request buildPartial() { bhz.netty.protobuf.RequestModule.Request result = new bhz.netty.protobuf.RequestModule.Request(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.id_ = id_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sequence_ = sequence_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.name_ = name_; if (((bitField0_ & 0x00000008) == 0x00000008)) { favorite_ = new com.google.protobuf.UnmodifiableLazyStringList( favorite_); bitField0_ = (bitField0_ & ~0x00000008); } result.favorite_ = favorite_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof bhz.netty.protobuf.RequestModule.Request) { return mergeFrom((bhz.netty.protobuf.RequestModule.Request)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(bhz.netty.protobuf.RequestModule.Request other) { if (other == bhz.netty.protobuf.RequestModule.Request.getDefaultInstance()) return this; if (other.hasId()) { bitField0_ |= 0x00000001; id_ = other.id_; onChanged(); } if (other.hasSequence()) { setSequence(other.getSequence()); } if (other.hasName()) { bitField0_ |= 0x00000004; name_ = other.name_; onChanged(); } if (!other.favorite_.isEmpty()) { if (favorite_.isEmpty()) { favorite_ = other.favorite_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureFavoriteIsMutable(); favorite_.addAll(other.favorite_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasId()) { return false; } if (!hasSequence()) { return false; } if (!hasName()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { bhz.netty.protobuf.RequestModule.Request parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (bhz.netty.protobuf.RequestModule.Request) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string id = 1;
      private java.lang.Object id_ = ""; /** * <code>required string id = 1;</code> */
      public boolean hasId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string id = 1;</code> */
      public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string id = 1;</code> */
      public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string id = 1;</code> */
      public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } /** * <code>required string id = 1;</code> */
      public Builder clearId() { bitField0_ = (bitField0_ & ~0x00000001); id_ = getDefaultInstance().getId(); onChanged(); return this; } /** * <code>required string id = 1;</code> */
      public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } // required int32 sequence = 2;
      private int sequence_ ; /** * <code>required int32 sequence = 2;</code> */
      public boolean hasSequence() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required int32 sequence = 2;</code> */
      public int getSequence() { return sequence_; } /** * <code>required int32 sequence = 2;</code> */
      public Builder setSequence(int value) { bitField0_ |= 0x00000002; sequence_ = value; onChanged(); return this; } /** * <code>required int32 sequence = 2;</code> */
      public Builder clearSequence() { bitField0_ = (bitField0_ & ~0x00000002); sequence_ = 0; onChanged(); return this; } // required string name = 3;
      private java.lang.Object name_ = ""; /** * <code>required string name = 3;</code> */
      public boolean hasName() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string name = 3;</code> */
      public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string name = 3;</code> */
      public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string name = 3;</code> */
      public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; name_ = value; onChanged(); return this; } /** * <code>required string name = 3;</code> */
      public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000004); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>required string name = 3;</code> */
      public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; name_ = value; onChanged(); return this; } // repeated string favorite = 4;
      private com.google.protobuf.LazyStringList favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureFavoriteIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { favorite_ = new com.google.protobuf.LazyStringArrayList(favorite_); bitField0_ |= 0x00000008; } } /** * <code>repeated string favorite = 4;</code> */
      public java.util.List<java.lang.String> getFavoriteList() { return java.util.Collections.unmodifiableList(favorite_); } /** * <code>repeated string favorite = 4;</code> */
      public int getFavoriteCount() { return favorite_.size(); } /** * <code>repeated string favorite = 4;</code> */
      public java.lang.String getFavorite(int index) { return favorite_.get(index); } /** * <code>repeated string favorite = 4;</code> */
      public com.google.protobuf.ByteString getFavoriteBytes(int index) { return favorite_.getByteString(index); } /** * <code>repeated string favorite = 4;</code> */
      public Builder setFavorite( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureFavoriteIsMutable(); favorite_.set(index, value); onChanged(); return this; } /** * <code>repeated string favorite = 4;</code> */
      public Builder addFavorite( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureFavoriteIsMutable(); favorite_.add(value); onChanged(); return this; } /** * <code>repeated string favorite = 4;</code> */
      public Builder addAllFavorite( java.lang.Iterable<java.lang.String> values) { ensureFavoriteIsMutable(); super.addAll(values, favorite_); onChanged(); return this; } /** * <code>repeated string favorite = 4;</code> */
      public Builder clearFavorite() { favorite_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * <code>repeated string favorite = 4;</code> */
      public Builder addFavoriteBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureFavoriteIsMutable(); favorite_.add(value); onChanged(); return this; } // @@protoc_insertion_point(builder_scope:Request)
 } static { defaultInstance = new Request(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Request)
 } private static com.google.protobuf.Descriptors.Descriptor internal_static_Request_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Request_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\023proto/request.proto\"G\n\007Request\022\n\n\002id\030\001" +
      " \002(\t\022\020\n\010sequence\030\002 \002(\005\022\014\n\004name\030\003 \002(\t\022\020\n\010" +
      "favorite\030\004 \003(\tB#\n\022bhz.netty.protobufB\rRe" +
      "questModule" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_Request_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Request_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Request_descriptor, new java.lang.String[] { "Id", "Sequence", "Name", "Favorite", }); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope)
}
View Code

 

 

3.4,Client.java

 1 package bhz.netty.protobuf.test;  2 
 3 import bhz.netty.protobuf.RequestModule;  4 import bhz.netty.protobuf.ResponseModule;  5 import bhz.netty.protobuf.ResponseModule.Response;  6 import io.netty.bootstrap.Bootstrap;  7 import io.netty.buffer.Unpooled;  8 import io.netty.channel.ChannelFuture;  9 import io.netty.channel.ChannelInitializer; 10 import io.netty.channel.EventLoopGroup; 11 import io.netty.channel.nio.NioEventLoopGroup; 12 import io.netty.channel.socket.SocketChannel; 13 import io.netty.channel.socket.nio.NioSocketChannel; 14 import io.netty.handler.codec.protobuf.ProtobufDecoder; 15 import io.netty.handler.codec.protobuf.ProtobufEncoder; 16 import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 17 import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 18 
19 public class Client { 20 
21     public static void main(String[] args) throws Exception { 22         //ONE: 23         //1 線程工做組
24         EventLoopGroup work = new NioEventLoopGroup(); 25         
26         //TWO: 27         //3 輔助類。用於幫助咱們建立NETTY服務
28         Bootstrap b = new Bootstrap(); 29         b.group(work)    //綁定工做線程組
30          .channel(NioSocketChannel.class)    //設置NIO的模式 31          // 初始化綁定服務通道
32          .handler(new ChannelInitializer<SocketChannel>() { 33  @Override 34             protected void initChannel(SocketChannel sc) throws Exception { 35                 
36                sc.pipeline().addLast(new ProtobufVarint32FrameDecoder()); 37 sc.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); 38 //編解碼使用: 39 sc.pipeline().addLast(new ProtobufDecoder(ResponseModule.Response.getDefaultInstance())); 40                 
41                 // 12345 == md5 加密 42                 // 一個對象 == 安裝 ProtobufEncoder 進行編碼 43                 
44                 // 解碼的時候: ProtobufDecoder (request/response)
45                 
46                 sc.pipeline().addLast(new ProtobufEncoder()); 47                 // 爲通道進行初始化: 數據傳輸過來的時候會進行攔截和執行
48                 sc.pipeline().addLast(new ClientHandler()); 49  } 50  }); 51         
52         ChannelFuture cf =  b.connect("127.0.0.1", 8765).syncUninterruptibly(); 53 
54         
55         
56         //釋放鏈接
57  cf.channel().closeFuture().sync(); 58  work.shutdownGracefully(); 59  } 60 }

 

3.5,ClientHandler.java

 1 package bhz.netty.protobuf.test;  2 
 3 import bhz.netty.protobuf.RequestModule;  4 import bhz.netty.protobuf.ResponseModule;  5 import io.netty.channel.ChannelHandlerContext;  6 import io.netty.channel.ChannelInboundHandlerAdapter;  7 import io.netty.util.ReferenceCountUtil;  8 
 9 public class ClientHandler extends ChannelInboundHandlerAdapter { 10 
11  @Override 12     public void channelActive(ChannelHandlerContext ctx) throws Exception { 13         System.err.println("通道激活。。。。"); 14         for(int i = 0; i < 10 ; i++){ 15  ctx.write(request(i)); 16  } 17  ctx.flush(); 18  } 19     
20     private RequestModule.Request request(int i){ 21         RequestModule.Request.Builder  builder = RequestModule.Request.newBuilder(); 22  builder 23         .setId(""+i) 24         .setName("" + i) 25  .setSequence(i) 26         .addFavorite("足球"+i) 27         .addFavorite("籃球"+i); 28         return builder.build(); 29  } 30     
31  @Override 32     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 33         try { 34             ResponseModule.Response response = (ResponseModule.Response)msg; 35             System.err.println("客戶端: " + response.getName()); 36         } finally { 37  ReferenceCountUtil.release(msg); 38  } 39  } 40     
41  @Override 42     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 43  throws Exception { 44  ctx.close(); 45  } 46     
47 }

 

3.6,response.proto

 1 option java_package = "bhz.netty.protobuf";  2 option java_outer_classname = "ResponseModule";  3 
 4 message Response {  5     required string id = 1;  6     
 7     required int32 code = 2;  8     
 9     required string name = 3; 10     
11     repeated string tags = 4; 12 }

 

3.7,ResponseModule.java

// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto/response.proto
 package bhz.netty.protobuf; public final class ResponseModule { private ResponseModule() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface ResponseOrBuilder extends com.google.protobuf.MessageOrBuilder { // required string id = 1;
    /** * <code>required string id = 1;</code> */ boolean hasId(); /** * <code>required string id = 1;</code> */ java.lang.String getId(); /** * <code>required string id = 1;</code> */ com.google.protobuf.ByteString getIdBytes(); // required int32 code = 2;
    /** * <code>required int32 code = 2;</code> */ boolean hasCode(); /** * <code>required int32 code = 2;</code> */
    int getCode(); // required string name = 3;
    /** * <code>required string name = 3;</code> */ boolean hasName(); /** * <code>required string name = 3;</code> */ java.lang.String getName(); /** * <code>required string name = 3;</code> */ com.google.protobuf.ByteString getNameBytes(); // repeated string tags = 4;
    /** * <code>repeated string tags = 4;</code> */ java.util.List<java.lang.String> getTagsList(); /** * <code>repeated string tags = 4;</code> */
    int getTagsCount(); /** * <code>repeated string tags = 4;</code> */ java.lang.String getTags(int index); /** * <code>repeated string tags = 4;</code> */ com.google.protobuf.ByteString getTagsBytes(int index); } /** * Protobuf type {@code Response} */
  public static final class Response extends com.google.protobuf.GeneratedMessage implements ResponseOrBuilder { // Use Response.newBuilder() to construct.
    private Response(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Response(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Response defaultInstance; public static Response getDefaultInstance() { return defaultInstance; } public Response getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Response( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; id_ = input.readBytes(); break; } case 16: { bitField0_ |= 0x00000002; code_ = input.readInt32(); break; } case 26: { bitField0_ |= 0x00000004; name_ = input.readBytes(); break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { tags_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000008; } tags_.add(input.readBytes()); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { tags_ = new com.google.protobuf.UnmodifiableLazyStringList(tags_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return bhz.netty.protobuf.ResponseModule.internal_static_Response_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return bhz.netty.protobuf.ResponseModule.internal_static_Response_fieldAccessorTable .ensureFieldAccessorsInitialized( bhz.netty.protobuf.ResponseModule.Response.class, bhz.netty.protobuf.ResponseModule.Response.Builder.class); } public static com.google.protobuf.Parser<Response> PARSER =
        new com.google.protobuf.AbstractParser<Response>() { public Response parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Response(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Response> getParserForType() { return PARSER; } private int bitField0_; // required string id = 1;
    public static final int ID_FIELD_NUMBER = 1; private java.lang.Object id_; /** * <code>required string id = 1;</code> */
    public boolean hasId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string id = 1;</code> */
    public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { id_ = s; } return s; } } /** * <code>required string id = 1;</code> */
    public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // required int32 code = 2;
    public static final int CODE_FIELD_NUMBER = 2; private int code_; /** * <code>required int32 code = 2;</code> */
    public boolean hasCode() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required int32 code = 2;</code> */
    public int getCode() { return code_; } // required string name = 3;
    public static final int NAME_FIELD_NUMBER = 3; private java.lang.Object name_; /** * <code>required string name = 3;</code> */
    public boolean hasName() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string name = 3;</code> */
    public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * <code>required string name = 3;</code> */
    public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // repeated string tags = 4;
    public static final int TAGS_FIELD_NUMBER = 4; private com.google.protobuf.LazyStringList tags_; /** * <code>repeated string tags = 4;</code> */
    public java.util.List<java.lang.String> getTagsList() { return tags_; } /** * <code>repeated string tags = 4;</code> */
    public int getTagsCount() { return tags_.size(); } /** * <code>repeated string tags = 4;</code> */
    public java.lang.String getTags(int index) { return tags_.get(index); } /** * <code>repeated string tags = 4;</code> */
    public com.google.protobuf.ByteString getTagsBytes(int index) { return tags_.getByteString(index); } private void initFields() { id_ = ""; code_ = 0; name_ = ""; tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasId()) { memoizedIsInitialized = 0; return false; } if (!hasCode()) { memoizedIsInitialized = 0; return false; } if (!hasName()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getIdBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeInt32(2, code_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getNameBytes()); } for (int i = 0; i < tags_.size(); i++) { output.writeBytes(4, tags_.getByteString(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getIdBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, code_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getNameBytes()); } { int dataSize = 0; for (int i = 0; i < tags_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream .computeBytesSizeNoTag(tags_.getByteString(i)); } size += dataSize; size += 1 * getTagsList().size(); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static bhz.netty.protobuf.ResponseModule.Response parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static bhz.netty.protobuf.ResponseModule.Response parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static bhz.netty.protobuf.ResponseModule.Response parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(bhz.netty.protobuf.ResponseModule.Response prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Response} */
    public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements bhz.netty.protobuf.ResponseModule.ResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return bhz.netty.protobuf.ResponseModule.internal_static_Response_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return bhz.netty.protobuf.ResponseModule.internal_static_Response_fieldAccessorTable .ensureFieldAccessorsInitialized( bhz.netty.protobuf.ResponseModule.Response.class, bhz.netty.protobuf.ResponseModule.Response.Builder.class); } // Construct using bhz.netty.protobuf.ResponseModule.Response.newBuilder()
      private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); id_ = ""; bitField0_ = (bitField0_ & ~0x00000001); code_ = 0; bitField0_ = (bitField0_ & ~0x00000002); name_ = ""; bitField0_ = (bitField0_ & ~0x00000004); tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return bhz.netty.protobuf.ResponseModule.internal_static_Response_descriptor; } public bhz.netty.protobuf.ResponseModule.Response getDefaultInstanceForType() { return bhz.netty.protobuf.ResponseModule.Response.getDefaultInstance(); } public bhz.netty.protobuf.ResponseModule.Response build() { bhz.netty.protobuf.ResponseModule.Response result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public bhz.netty.protobuf.ResponseModule.Response buildPartial() { bhz.netty.protobuf.ResponseModule.Response result = new bhz.netty.protobuf.ResponseModule.Response(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.id_ = id_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.code_ = code_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.name_ = name_; if (((bitField0_ & 0x00000008) == 0x00000008)) { tags_ = new com.google.protobuf.UnmodifiableLazyStringList( tags_); bitField0_ = (bitField0_ & ~0x00000008); } result.tags_ = tags_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof bhz.netty.protobuf.ResponseModule.Response) { return mergeFrom((bhz.netty.protobuf.ResponseModule.Response)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(bhz.netty.protobuf.ResponseModule.Response other) { if (other == bhz.netty.protobuf.ResponseModule.Response.getDefaultInstance()) return this; if (other.hasId()) { bitField0_ |= 0x00000001; id_ = other.id_; onChanged(); } if (other.hasCode()) { setCode(other.getCode()); } if (other.hasName()) { bitField0_ |= 0x00000004; name_ = other.name_; onChanged(); } if (!other.tags_.isEmpty()) { if (tags_.isEmpty()) { tags_ = other.tags_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureTagsIsMutable(); tags_.addAll(other.tags_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasId()) { return false; } if (!hasCode()) { return false; } if (!hasName()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { bhz.netty.protobuf.ResponseModule.Response parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (bhz.netty.protobuf.ResponseModule.Response) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string id = 1;
      private java.lang.Object id_ = ""; /** * <code>required string id = 1;</code> */
      public boolean hasId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string id = 1;</code> */
      public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string id = 1;</code> */
      public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string id = 1;</code> */
      public Builder setId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } /** * <code>required string id = 1;</code> */
      public Builder clearId() { bitField0_ = (bitField0_ & ~0x00000001); id_ = getDefaultInstance().getId(); onChanged(); return this; } /** * <code>required string id = 1;</code> */
      public Builder setIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; id_ = value; onChanged(); return this; } // required int32 code = 2;
      private int code_ ; /** * <code>required int32 code = 2;</code> */
      public boolean hasCode() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required int32 code = 2;</code> */
      public int getCode() { return code_; } /** * <code>required int32 code = 2;</code> */
      public Builder setCode(int value) { bitField0_ |= 0x00000002; code_ = value; onChanged(); return this; } /** * <code>required int32 code = 2;</code> */
      public Builder clearCode() { bitField0_ = (bitField0_ & ~0x00000002); code_ = 0; onChanged(); return this; } // required string name = 3;
      private java.lang.Object name_ = ""; /** * <code>required string name = 3;</code> */
      public boolean hasName() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required string name = 3;</code> */
      public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string name = 3;</code> */
      public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string name = 3;</code> */
      public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; name_ = value; onChanged(); return this; } /** * <code>required string name = 3;</code> */
      public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000004); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>required string name = 3;</code> */
      public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; name_ = value; onChanged(); return this; } // repeated string tags = 4;
      private com.google.protobuf.LazyStringList tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureTagsIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { tags_ = new com.google.protobuf.LazyStringArrayList(tags_); bitField0_ |= 0x00000008; } } /** * <code>repeated string tags = 4;</code> */
      public java.util.List<java.lang.String> getTagsList() { return java.util.Collections.unmodifiableList(tags_); } /** * <code>repeated string tags = 4;</code> */
      public int getTagsCount() { return tags_.size(); } /** * <code>repeated string tags = 4;</code> */
      public java.lang.String getTags(int index) { return tags_.get(index); } /** * <code>repeated string tags = 4;</code> */
      public com.google.protobuf.ByteString getTagsBytes(int index) { return tags_.getByteString(index); } /** * <code>repeated string tags = 4;</code> */
      public Builder setTags( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTagsIsMutable(); tags_.set(index, value); onChanged(); return this; } /** * <code>repeated string tags = 4;</code> */
      public Builder addTags( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTagsIsMutable(); tags_.add(value); onChanged(); return this; } /** * <code>repeated string tags = 4;</code> */
      public Builder addAllTags( java.lang.Iterable<java.lang.String> values) { ensureTagsIsMutable(); super.addAll(values, tags_); onChanged(); return this; } /** * <code>repeated string tags = 4;</code> */
      public Builder clearTags() { tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * <code>repeated string tags = 4;</code> */
      public Builder addTagsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } ensureTagsIsMutable(); tags_.add(value); onChanged(); return this; } // @@protoc_insertion_point(builder_scope:Response)
 } static { defaultInstance = new Response(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Response)
 } private static com.google.protobuf.Descriptors.Descriptor internal_static_Response_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Response_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\024proto/response.proto\"@\n\010Response\022\n\n\002id" +
      "\030\001 \002(\t\022\014\n\004code\030\002 \002(\005\022\014\n\004name\030\003 \002(\t\022\014\n\004ta" +
      "gs\030\004 \003(\tB$\n\022bhz.netty.protobufB\016Response" +
      "Module" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_Response_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Response_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Response_descriptor, new java.lang.String[] { "Id", "Code", "Name", "Tags", }); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope)
}
View Code

 

 

3.8,Server.java

 1 package bhz.netty.protobuf.test;  2 
 3 
 4 import bhz.netty.protobuf.RequestModule;  5 import io.netty.bootstrap.ServerBootstrap;  6 import io.netty.channel.ChannelFuture;  7 import io.netty.channel.ChannelInitializer;  8 import io.netty.channel.ChannelOption;  9 import io.netty.channel.EventLoopGroup; 10 import io.netty.channel.nio.NioEventLoopGroup; 11 import io.netty.channel.socket.SocketChannel; 12 import io.netty.channel.socket.nio.NioServerSocketChannel; 13 import io.netty.handler.codec.protobuf.ProtobufDecoder; 14 import io.netty.handler.codec.protobuf.ProtobufEncoder; 15 import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 16 import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 17 
18 public class Server { 19 
20     
21     public static void main(String[] args) throws Exception { 22         //ONE: 23         //1 用於接受客戶端鏈接的線程工做組
24         EventLoopGroup boss = new NioEventLoopGroup(); 25         //2 用於對接受客戶端鏈接讀寫操做的線程工做組
26         EventLoopGroup work = new NioEventLoopGroup(); 27         
28         //TWO: 29         //3 輔助類。用於幫助咱們建立NETTY服務
30         ServerBootstrap b = new ServerBootstrap(); 31         b.group(boss, work)    //綁定兩個工做線程組
32          .channel(NioServerSocketChannel.class)    //設置NIO的模式
33          .option(ChannelOption.SO_BACKLOG, 1024)    //設置TCP緩衝區 34          //.option(ChannelOption.SO_SNDBUF, 32*1024) // 設置發送數據的緩存大小
35          .option(ChannelOption.SO_RCVBUF, 32*1024)    // 設置接受數據的緩存大小
36          .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)    // 設置保持鏈接
37          .childOption(ChannelOption.SO_SNDBUF, 32*1024) 38          // 初始化綁定服務通道
39          .childHandler(new ChannelInitializer<SocketChannel>() { 40  @Override 41             protected void initChannel(SocketChannel sc) throws Exception { 42     //識別數據使用: 43 sc.pipeline().addLast(new ProtobufVarint32FrameDecoder()); 44 sc.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); 45 //編解碼使用: 46 sc.pipeline().addLast(new ProtobufDecoder(RequestModule.Request.getDefaultInstance())); 47                 
48                 sc.pipeline().addLast(new ProtobufEncoder()); 49                 
50                 // 爲通道進行初始化: 數據傳輸過來的時候會進行攔截和執行
51                 sc.pipeline().addLast(new ServerHandler()); 52  } 53  }); 54         
55         ChannelFuture cf = b.bind(8765).sync(); 56         
57         
58         
59         //釋放鏈接
60  cf.channel().closeFuture().sync(); 61  work.shutdownGracefully(); 62  boss.shutdownGracefully(); 63  } 64 }

 

3.9,ServerHandler.java

 1 package bhz.netty.protobuf.test;  2 
 3 import bhz.netty.protobuf.RequestModule;  4 import bhz.netty.protobuf.ResponseModule;  5 import io.netty.buffer.ByteBuf;  6 import io.netty.buffer.Unpooled;  7 import io.netty.channel.ChannelFutureListener;  8 import io.netty.channel.ChannelHandlerContext;  9 import io.netty.channel.ChannelInboundHandlerAdapter; 10 import io.netty.util.ReferenceCountUtil; 11 
12 public class ServerHandler extends ChannelInboundHandlerAdapter { 13 
14     /** 15  * 當咱們的通道里有數據進行讀取的時候 觸發的監聽方法 16      */
17  @Override 18     public void channelRead(ChannelHandlerContext ctx /*NETTY服務上下文*/, Object msg /*實際的傳輸數據*/) throws Exception { 19         
20         RequestModule.Request request = (RequestModule.Request)msg; 21         
22         System.err.println("服務器: " + request.getName()); 23         
24  ctx.writeAndFlush(response(request.getId())); 25         
26  } 27     
28     private ResponseModule.Response response(String id) { 29         ResponseModule.Response.Builder  builder = ResponseModule.Response.newBuilder(); 30  builder 31         .setId("響應"+ id) 32  .setCode(Integer.parseInt(id)) 33         .setName("響應信息" + id) 34         .addTags("tagA") 35         .addTags("tagB"); 36         return builder.build(); 37  } 38 
39  @Override 40     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 41        System.err.println("--------數據讀取完畢----------"); 42  } 43     
44  @Override 45     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) 46  throws Exception { 47         System.err.println("--------數據讀異常----------"); 48  ctx.close(); 49  } 50 
51     
52 }

 

 服務端結果:

Java HotSpot(TM) 64-Bit Server VM warning: MaxNewSize (524288k) is equal to or greater than the entire heap (524288k).  A new generation size of 524224k will be used. 服務器: 張0 服務器: 張1 服務器: 張2 服務器: 張3 服務器: 張4 服務器: 張5 服務器: 張6 服務器: 張7 服務器: 張8 服務器: 張9 --------數據讀取完畢----------

 

客戶端結果: 

 1 通道激活。。。。  2 客戶端: 響應信息0  3 客戶端: 響應信息1  4 客戶端: 響應信息2  5 客戶端: 響應信息3  6 客戶端: 響應信息4  7 客戶端: 響應信息5  8 客戶端: 響應信息6  9 客戶端: 響應信息7 10 客戶端: 響應信息8 11 客戶端: 響應信息9
相關文章
相關標籤/搜索