1 需求:
1、客户端可以随机发送Student POJO 、Worker POJO 对象到服务器(通过protobuf编码)
2、服务端能接收 Student POJO 、Worker POJO 对象(需要判断是哪种类型),并显示信息(通过ProtoBuf解码)
2 开发
2.1 编写proto文件
MyDate.proto
syntax = "proto3"; option optimize_for = SPEED;//加快解析 option java_package = "com.jay.atguigu.netty.codec2";//指定生成到哪个包下 option java_outer_classname = "MyDataInfo";//外部类名,文件名 //protobuf 可以使用message 管理其他的 message message MyMessage{//定义一个枚举类型enum DataType {StudentType = 0;//在proto3中,要求enum的编号从0开始WorkerType = 1;}//用data_type来标识传入的是哪种枚举类型DataType data_type = 1;//表示每次枚举最多只能出现其中的一个,节省空间oneof dataBody {Student student = 2;Worker worker = 3;} } message Student {int32 id = 1;string name = 2; } message Worker {string name = 1;int32 age = 2; }
执行命令,生成对应的Java文件 MyDataInfo.java
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: MyDate.protopackage com.jay.atguigu.netty.codec2;public final class MyDataInfo {private MyDataInfo() {}public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);}public interface MyMessageOrBuilder extends// @@protoc_insertion_point(interface_extends:MyMessage)com.google.protobuf.MessageOrBuilder {/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/int getDataTypeValue();/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/MyMessage.DataType getDataType();/*** <code>.Student student = 2;</code>*/boolean hasStudent();/*** <code>.Student student = 2;</code>*/Student getStudent();/*** <code>.Student student = 2;</code>*/StudentOrBuilder getStudentOrBuilder();/*** <code>.Worker worker = 3;</code>*/boolean hasWorker();/*** <code>.Worker worker = 3;</code>*/Worker getWorker();/*** <code>.Worker worker = 3;</code>*/WorkerOrBuilder getWorkerOrBuilder();public MyMessage.DataBodyCase getDataBodyCase();}/*** <pre>*protobuf 可以使用message 管理其他的 message* </pre>** Protobuf type {@code MyMessage}*/public static final class MyMessage extendscom.google.protobuf.GeneratedMessageV3 implements// @@protoc_insertion_point(message_implements:MyMessage)MyMessageOrBuilder {private static final long serialVersionUID = 0L;// Use MyMessage.newBuilder() to construct.private MyMessage(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {super(builder);}private MyMessage() {dataType_ = 0;}@Overridepublic final com.google.protobuf.UnknownFieldSetgetUnknownFields() {return this.unknownFields;}private MyMessage(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {this();if (extensionRegistry == null) {throw new NullPointerException();}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;case 8: {int rawValue = input.readEnum();dataType_ = rawValue;break;}case 18: {Student.Builder subBuilder = null;if (dataBodyCase_ == 2) {subBuilder = ((Student) dataBody_).toBuilder();}dataBody_ =input.readMessage(Student.parser(), extensionRegistry);if (subBuilder != null) {subBuilder.mergeFrom((Student) dataBody_);dataBody_ = subBuilder.buildPartial();}dataBodyCase_ = 2;break;}case 26: {Worker.Builder subBuilder = null;if (dataBodyCase_ == 3) {subBuilder = ((Worker) dataBody_).toBuilder();}dataBody_ =input.readMessage(Worker.parser(), extensionRegistry);if (subBuilder != null) {subBuilder.mergeFrom((Worker) dataBody_);dataBody_ = subBuilder.buildPartial();}dataBodyCase_ = 3;break;}default: {if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {done = true;}break;}}}} catch (com.google.protobuf.InvalidProtocolBufferException e) {throw e.setUnfinishedMessage(this);} catch (java.io.IOException e) {throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);} finally {this.unknownFields = unknownFields.build();makeExtensionsImmutable();}}public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return MyDataInfo.internal_static_MyMessage_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return MyDataInfo.internal_static_MyMessage_fieldAccessorTable.ensureFieldAccessorsInitialized(MyMessage.class, Builder.class);}/*** <pre>*定义一个枚举类型* </pre>** Protobuf enum {@code MyMessage.DataType}*/public enum DataTypeimplements com.google.protobuf.ProtocolMessageEnum {/*** <pre>*在proto3中,要求enum的编号从0开始* </pre>** <code>StudentType = 0;</code>*/StudentType(0),/*** <code>WorkerType = 1;</code>*/WorkerType(1),UNRECOGNIZED(-1),;/*** <pre>*在proto3中,要求enum的编号从0开始* </pre>** <code>StudentType = 0;</code>*/public static final int StudentType_VALUE = 0;/*** <code>WorkerType = 1;</code>*/public static final int WorkerType_VALUE = 1;public final int getNumber() {if (this == UNRECOGNIZED) {throw new IllegalArgumentException("Can't get the number of an unknown enum value.");}return value;}/*** @deprecated Use {@link #forNumber(int)} instead.*/@Deprecatedpublic static DataType valueOf(int value) {return forNumber(value);}public static DataType forNumber(int value) {switch (value) {case 0: return StudentType;case 1: return WorkerType;default: return null;}}public static com.google.protobuf.Internal.EnumLiteMap<DataType>internalGetValueMap() {return internalValueMap;}private static final com.google.protobuf.Internal.EnumLiteMap<DataType> internalValueMap =new com.google.protobuf.Internal.EnumLiteMap<DataType>() {public DataType findValueByNumber(int number) {return DataType.forNumber(number);}};public final com.google.protobuf.Descriptors.EnumValueDescriptorgetValueDescriptor() {return getDescriptor().getValues().get(ordinal());}public final com.google.protobuf.Descriptors.EnumDescriptorgetDescriptorForType() {return getDescriptor();}public static final com.google.protobuf.Descriptors.EnumDescriptorgetDescriptor() {return MyMessage.getDescriptor().getEnumTypes().get(0);}private static final DataType[] VALUES = values();public static DataType valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {if (desc.getType() != getDescriptor()) {throw new IllegalArgumentException("EnumValueDescriptor is not for this type.");}if (desc.getIndex() == -1) {return UNRECOGNIZED;}return VALUES[desc.getIndex()];}private final int value;private DataType(int value) {this.value = value;}// @@protoc_insertion_point(enum_scope:MyMessage.DataType)}private int dataBodyCase_ = 0;private Object dataBody_;public enum DataBodyCaseimplements com.google.protobuf.Internal.EnumLite {STUDENT(2),WORKER(3),DATABODY_NOT_SET(0);private final int value;private DataBodyCase(int value) {this.value = value;}/*** @deprecated Use {@link #forNumber(int)} instead.*/@Deprecatedpublic static DataBodyCase valueOf(int value) {return forNumber(value);}public static DataBodyCase forNumber(int value) {switch (value) {case 2: return STUDENT;case 3: return WORKER;case 0: return DATABODY_NOT_SET;default: return null;}}public int getNumber() {return this.value;}};public DataBodyCasegetDataBodyCase() {return DataBodyCase.forNumber(dataBodyCase_);}public static final int DATA_TYPE_FIELD_NUMBER = 1;private int dataType_;/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public int getDataTypeValue() {return dataType_;}/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public DataType getDataType() {@SuppressWarnings("deprecation")DataType result = DataType.valueOf(dataType_);return result == null ? DataType.UNRECOGNIZED : result;}public static final int STUDENT_FIELD_NUMBER = 2;/*** <code>.Student student = 2;</code>*/public boolean hasStudent() {return dataBodyCase_ == 2;}/*** <code>.Student student = 2;</code>*/public Student getStudent() {if (dataBodyCase_ == 2) {return (Student) dataBody_;}return Student.getDefaultInstance();}/*** <code>.Student student = 2;</code>*/public StudentOrBuilder getStudentOrBuilder() {if (dataBodyCase_ == 2) {return (Student) dataBody_;}return Student.getDefaultInstance();}public static final int WORKER_FIELD_NUMBER = 3;/*** <code>.Worker worker = 3;</code>*/public boolean hasWorker() {return dataBodyCase_ == 3;}/*** <code>.Worker worker = 3;</code>*/public Worker getWorker() {if (dataBodyCase_ == 3) {return (Worker) dataBody_;}return Worker.getDefaultInstance();}/*** <code>.Worker worker = 3;</code>*/public WorkerOrBuilder getWorkerOrBuilder() {if (dataBodyCase_ == 3) {return (Worker) dataBody_;}return Worker.getDefaultInstance();}private byte memoizedIsInitialized = -1;@Overridepublic final boolean isInitialized() {byte isInitialized = memoizedIsInitialized;if (isInitialized == 1) return true;if (isInitialized == 0) return false;memoizedIsInitialized = 1;return true;}@Overridepublic void writeTo(com.google.protobuf.CodedOutputStream output)throws java.io.IOException {if (dataType_ != DataType.StudentType.getNumber()) {output.writeEnum(1, dataType_);}if (dataBodyCase_ == 2) {output.writeMessage(2, (Student) dataBody_);}if (dataBodyCase_ == 3) {output.writeMessage(3, (Worker) dataBody_);}unknownFields.writeTo(output);}@Overridepublic int getSerializedSize() {int size = memoizedSize;if (size != -1) return size;size = 0;if (dataType_ != DataType.StudentType.getNumber()) {size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, dataType_);}if (dataBodyCase_ == 2) {size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, (Student) dataBody_);}if (dataBodyCase_ == 3) {size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, (Worker) dataBody_);}size += unknownFields.getSerializedSize();memoizedSize = size;return size;}@Overridepublic boolean equals(final Object obj) {if (obj == this) {return true;}if (!(obj instanceof MyMessage)) {return super.equals(obj);}MyMessage other = (MyMessage) obj;boolean result = true;result = result && dataType_ == other.dataType_;result = result && getDataBodyCase().equals(other.getDataBodyCase());if (!result) return false;switch (dataBodyCase_) {case 2:result = result && getStudent().equals(other.getStudent());break;case 3:result = result && getWorker().equals(other.getWorker());break;case 0:default:}result = result && unknownFields.equals(other.unknownFields);return result;}@Overridepublic int hashCode() {if (memoizedHashCode != 0) {return memoizedHashCode;}int hash = 41;hash = (19 * hash) + getDescriptor().hashCode();hash = (37 * hash) + DATA_TYPE_FIELD_NUMBER;hash = (53 * hash) + dataType_;switch (dataBodyCase_) {case 2:hash = (37 * hash) + STUDENT_FIELD_NUMBER;hash = (53 * hash) + getStudent().hashCode();break;case 3:hash = (37 * hash) + WORKER_FIELD_NUMBER;hash = (53 * hash) + getWorker().hashCode();break;case 0:default:}hash = (29 * hash) + unknownFields.hashCode();memoizedHashCode = hash;return hash;}public static MyMessage parseFrom(java.nio.ByteBuffer data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static MyMessage parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static MyMessage parseFrom(com.google.protobuf.ByteString data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static MyMessage parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static MyMessage parseFrom(byte[] data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static MyMessage parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static MyMessage parseFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static MyMessage parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}public static MyMessage parseDelimitedFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);}public static MyMessage parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);}public static MyMessage parseFrom(com.google.protobuf.CodedInputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static MyMessage parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}@Overridepublic Builder newBuilderForType() { return newBuilder(); }public static Builder newBuilder() {return DEFAULT_INSTANCE.toBuilder();}public static Builder newBuilder(MyMessage prototype) {return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);}@Overridepublic Builder toBuilder() {return this == DEFAULT_INSTANCE? new Builder() : new Builder().mergeFrom(this);}@Overrideprotected Builder newBuilderForType(BuilderParent parent) {Builder builder = new Builder(parent);return builder;}/*** <pre>*protobuf 可以使用message 管理其他的 message* </pre>** Protobuf type {@code MyMessage}*/public static final class Builder extendscom.google.protobuf.GeneratedMessageV3.Builder<Builder> implements// @@protoc_insertion_point(builder_implements:MyMessage)MyMessageOrBuilder {public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return MyDataInfo.internal_static_MyMessage_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return MyDataInfo.internal_static_MyMessage_fieldAccessorTable.ensureFieldAccessorsInitialized(MyMessage.class, Builder.class);}// Construct using com.jay.atguigu.netty.codec2.MyDataInfo.MyMessage.newBuilder()private Builder() {maybeForceBuilderInitialization();}private Builder(BuilderParent parent) {super(parent);maybeForceBuilderInitialization();}private void maybeForceBuilderInitialization() {if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}}@Overridepublic Builder clear() {super.clear();dataType_ = 0;dataBodyCase_ = 0;dataBody_ = null;return this;}@Overridepublic com.google.protobuf.Descriptors.DescriptorgetDescriptorForType() {return MyDataInfo.internal_static_MyMessage_descriptor;}@Overridepublic MyMessage getDefaultInstanceForType() {return MyMessage.getDefaultInstance();}@Overridepublic MyMessage build() {MyMessage result = buildPartial();if (!result.isInitialized()) {throw newUninitializedMessageException(result);}return result;}@Overridepublic MyMessage buildPartial() {MyMessage result = new MyMessage(this);result.dataType_ = dataType_;if (dataBodyCase_ == 2) {if (studentBuilder_ == null) {result.dataBody_ = dataBody_;} else {result.dataBody_ = studentBuilder_.build();}}if (dataBodyCase_ == 3) {if (workerBuilder_ == null) {result.dataBody_ = dataBody_;} else {result.dataBody_ = workerBuilder_.build();}}result.dataBodyCase_ = dataBodyCase_;onBuilt();return result;}@Overridepublic Builder clone() {return (Builder) super.clone();}@Overridepublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.setField(field, value);}@Overridepublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {return (Builder) super.clearField(field);}@Overridepublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {return (Builder) super.clearOneof(oneof);}@Overridepublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index, Object value) {return (Builder) super.setRepeatedField(field, index, value);}@Overridepublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.addRepeatedField(field, value);}@Overridepublic Builder mergeFrom(com.google.protobuf.Message other) {if (other instanceof MyMessage) {return mergeFrom((MyMessage)other);} else {super.mergeFrom(other);return this;}}public Builder mergeFrom(MyMessage other) {if (other == MyMessage.getDefaultInstance()) return this;if (other.dataType_ != 0) {setDataTypeValue(other.getDataTypeValue());}switch (other.getDataBodyCase()) {case STUDENT: {mergeStudent(other.getStudent());break;}case WORKER: {mergeWorker(other.getWorker());break;}case DATABODY_NOT_SET: {break;}}this.mergeUnknownFields(other.unknownFields);onChanged();return this;}@Overridepublic final boolean isInitialized() {return true;}@Overridepublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {MyMessage parsedMessage = null;try {parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);} catch (com.google.protobuf.InvalidProtocolBufferException e) {parsedMessage = (MyMessage) e.getUnfinishedMessage();throw e.unwrapIOException();} finally {if (parsedMessage != null) {mergeFrom(parsedMessage);}}return this;}private int dataBodyCase_ = 0;private Object dataBody_;public DataBodyCasegetDataBodyCase() {return DataBodyCase.forNumber(dataBodyCase_);}public Builder clearDataBody() {dataBodyCase_ = 0;dataBody_ = null;onChanged();return this;}private int dataType_ = 0;/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public int getDataTypeValue() {return dataType_;}/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public Builder setDataTypeValue(int value) {dataType_ = value;onChanged();return this;}/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public DataType getDataType() {@SuppressWarnings("deprecation")DataType result = DataType.valueOf(dataType_);return result == null ? DataType.UNRECOGNIZED : result;}/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public Builder setDataType(DataType value) {if (value == null) {throw new NullPointerException();}dataType_ = value.getNumber();onChanged();return this;}/*** <pre>*用data_type来标识传入的是哪种枚举类型* </pre>** <code>.MyMessage.DataType data_type = 1;</code>*/public Builder clearDataType() {dataType_ = 0;onChanged();return this;}private com.google.protobuf.SingleFieldBuilderV3<Student, Student.Builder, StudentOrBuilder> studentBuilder_;/*** <code>.Student student = 2;</code>*/public boolean hasStudent() {return dataBodyCase_ == 2;}/*** <code>.Student student = 2;</code>*/public Student getStudent() {if (studentBuilder_ == null) {if (dataBodyCase_ == 2) {return (Student) dataBody_;}return Student.getDefaultInstance();} else {if (dataBodyCase_ == 2) {return studentBuilder_.getMessage();}return Student.getDefaultInstance();}}/*** <code>.Student student = 2;</code>*/public Builder setStudent(Student value) {if (studentBuilder_ == null) {if (value == null) {throw new NullPointerException();}dataBody_ = value;onChanged();} else {studentBuilder_.setMessage(value);}dataBodyCase_ = 2;return this;}/*** <code>.Student student = 2;</code>*/public Builder setStudent(Student.Builder builderForValue) {if (studentBuilder_ == null) {dataBody_ = builderForValue.build();onChanged();} else {studentBuilder_.setMessage(builderForValue.build());}dataBodyCase_ = 2;return this;}/*** <code>.Student student = 2;</code>*/public Builder mergeStudent(Student value) {if (studentBuilder_ == null) {if (dataBodyCase_ == 2 &&dataBody_ != Student.getDefaultInstance()) {dataBody_ = Student.newBuilder((Student) dataBody_).mergeFrom(value).buildPartial();} else {dataBody_ = value;}onChanged();} else {if (dataBodyCase_ == 2) {studentBuilder_.mergeFrom(value);}studentBuilder_.setMessage(value);}dataBodyCase_ = 2;return this;}/*** <code>.Student student = 2;</code>*/public Builder clearStudent() {if (studentBuilder_ == null) {if (dataBodyCase_ == 2) {dataBodyCase_ = 0;dataBody_ = null;onChanged();}} else {if (dataBodyCase_ == 2) {dataBodyCase_ = 0;dataBody_ = null;}studentBuilder_.clear();}return this;}/*** <code>.Student student = 2;</code>*/public Student.Builder getStudentBuilder() {return getStudentFieldBuilder().getBuilder();}/*** <code>.Student student = 2;</code>*/public StudentOrBuilder getStudentOrBuilder() {if ((dataBodyCase_ == 2) && (studentBuilder_ != null)) {return studentBuilder_.getMessageOrBuilder();} else {if (dataBodyCase_ == 2) {return (Student) dataBody_;}return Student.getDefaultInstance();}}/*** <code>.Student student = 2;</code>*/private com.google.protobuf.SingleFieldBuilderV3<Student, Student.Builder, StudentOrBuilder> getStudentFieldBuilder() {if (studentBuilder_ == null) {if (!(dataBodyCase_ == 2)) {dataBody_ = Student.getDefaultInstance();}studentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<Student, Student.Builder, StudentOrBuilder>((Student) dataBody_,getParentForChildren(),isClean());dataBody_ = null;}dataBodyCase_ = 2;onChanged();;return studentBuilder_;}private com.google.protobuf.SingleFieldBuilderV3<Worker, Worker.Builder, WorkerOrBuilder> workerBuilder_;/*** <code>.Worker worker = 3;</code>*/public boolean hasWorker() {return dataBodyCase_ == 3;}/*** <code>.Worker worker = 3;</code>*/public Worker getWorker() {if (workerBuilder_ == null) {if (dataBodyCase_ == 3) {return (Worker) dataBody_;}return Worker.getDefaultInstance();} else {if (dataBodyCase_ == 3) {return workerBuilder_.getMessage();}return Worker.getDefaultInstance();}}/*** <code>.Worker worker = 3;</code>*/public Builder setWorker(Worker value) {if (workerBuilder_ == null) {if (value == null) {throw new NullPointerException();}dataBody_ = value;onChanged();} else {workerBuilder_.setMessage(value);}dataBodyCase_ = 3;return this;}/*** <code>.Worker worker = 3;</code>*/public Builder setWorker(Worker.Builder builderForValue) {if (workerBuilder_ == null) {dataBody_ = builderForValue.build();onChanged();} else {workerBuilder_.setMessage(builderForValue.build());}dataBodyCase_ = 3;return this;}/*** <code>.Worker worker = 3;</code>*/public Builder mergeWorker(Worker value) {if (workerBuilder_ == null) {if (dataBodyCase_ == 3 &&dataBody_ != Worker.getDefaultInstance()) {dataBody_ = Worker.newBuilder((Worker) dataBody_).mergeFrom(value).buildPartial();} else {dataBody_ = value;}onChanged();} else {if (dataBodyCase_ == 3) {workerBuilder_.mergeFrom(value);}workerBuilder_.setMessage(value);}dataBodyCase_ = 3;return this;}/*** <code>.Worker worker = 3;</code>*/public Builder clearWorker() {if (workerBuilder_ == null) {if (dataBodyCase_ == 3) {dataBodyCase_ = 0;dataBody_ = null;onChanged();}} else {if (dataBodyCase_ == 3) {dataBodyCase_ = 0;dataBody_ = null;}workerBuilder_.clear();}return this;}/*** <code>.Worker worker = 3;</code>*/public Worker.Builder getWorkerBuilder() {return getWorkerFieldBuilder().getBuilder();}/*** <code>.Worker worker = 3;</code>*/public WorkerOrBuilder getWorkerOrBuilder() {if ((dataBodyCase_ == 3) && (workerBuilder_ != null)) {return workerBuilder_.getMessageOrBuilder();} else {if (dataBodyCase_ == 3) {return (Worker) dataBody_;}return Worker.getDefaultInstance();}}/*** <code>.Worker worker = 3;</code>*/private com.google.protobuf.SingleFieldBuilderV3<Worker, Worker.Builder, WorkerOrBuilder> getWorkerFieldBuilder() {if (workerBuilder_ == null) {if (!(dataBodyCase_ == 3)) {dataBody_ = Worker.getDefaultInstance();}workerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<Worker, Worker.Builder, WorkerOrBuilder>((Worker) dataBody_,getParentForChildren(),isClean());dataBody_ = null;}dataBodyCase_ = 3;onChanged();;return workerBuilder_;}@Overridepublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.setUnknownFieldsProto3(unknownFields);}@Overridepublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.mergeUnknownFields(unknownFields);}// @@protoc_insertion_point(builder_scope:MyMessage)}// @@protoc_insertion_point(class_scope:MyMessage)private static final MyMessage DEFAULT_INSTANCE;static {DEFAULT_INSTANCE = new MyMessage();}public static MyMessage getDefaultInstance() {return DEFAULT_INSTANCE;}private static final com.google.protobuf.Parser<MyMessage>PARSER = new com.google.protobuf.AbstractParser<MyMessage>() {@Overridepublic MyMessage parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return new MyMessage(input, extensionRegistry);}};public static com.google.protobuf.Parser<MyMessage> parser() {return PARSER;}@Overridepublic com.google.protobuf.Parser<MyMessage> getParserForType() {return PARSER;}@Overridepublic MyMessage getDefaultInstanceForType() {return DEFAULT_INSTANCE;}}public interface StudentOrBuilder extends// @@protoc_insertion_point(interface_extends:Student)com.google.protobuf.MessageOrBuilder {/*** <code>int32 id = 1;</code>*/int getId();/*** <code>string name = 2;</code>*/String getName();/*** <code>string name = 2;</code>*/com.google.protobuf.ByteStringgetNameBytes();}/*** Protobuf type {@code Student}*/public static final class Student extendscom.google.protobuf.GeneratedMessageV3 implements// @@protoc_insertion_point(message_implements:Student)StudentOrBuilder {private static final long serialVersionUID = 0L;// Use Student.newBuilder() to construct.private Student(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {super(builder);}private Student() {id_ = 0;name_ = "";}@Overridepublic final com.google.protobuf.UnknownFieldSetgetUnknownFields() {return this.unknownFields;}private Student(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {this();if (extensionRegistry == null) {throw new NullPointerException();}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;case 8: {id_ = input.readInt32();break;}case 18: {String s = input.readStringRequireUtf8();name_ = s;break;}default: {if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {done = true;}break;}}}} catch (com.google.protobuf.InvalidProtocolBufferException e) {throw e.setUnfinishedMessage(this);} catch (java.io.IOException e) {throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);} finally {this.unknownFields = unknownFields.build();makeExtensionsImmutable();}}public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return MyDataInfo.internal_static_Student_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return MyDataInfo.internal_static_Student_fieldAccessorTable.ensureFieldAccessorsInitialized(Student.class, Builder.class);}public static final int ID_FIELD_NUMBER = 1;private int id_;/*** <code>int32 id = 1;</code>*/public int getId() {return id_;}public static final int NAME_FIELD_NUMBER = 2;private volatile Object name_;/*** <code>string name = 2;</code>*/public String getName() {Object ref = name_;if (ref instanceof String) {return (String) ref;} else {com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;}}/*** <code>string name = 2;</code>*/public com.google.protobuf.ByteStringgetNameBytes() {Object ref = name_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);name_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}private byte memoizedIsInitialized = -1;@Overridepublic final boolean isInitialized() {byte isInitialized = memoizedIsInitialized;if (isInitialized == 1) return true;if (isInitialized == 0) return false;memoizedIsInitialized = 1;return true;}@Overridepublic void writeTo(com.google.protobuf.CodedOutputStream output)throws java.io.IOException {if (id_ != 0) {output.writeInt32(1, id_);}if (!getNameBytes().isEmpty()) {com.google.protobuf.GeneratedMessageV3.writeString(output, 2, name_);}unknownFields.writeTo(output);}@Overridepublic int getSerializedSize() {int size = memoizedSize;if (size != -1) return size;size = 0;if (id_ != 0) {size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, id_);}if (!getNameBytes().isEmpty()) {size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, name_);}size += unknownFields.getSerializedSize();memoizedSize = size;return size;}@Overridepublic boolean equals(final Object obj) {if (obj == this) {return true;}if (!(obj instanceof Student)) {return super.equals(obj);}Student other = (Student) obj;boolean result = true;result = result && (getId()== other.getId());result = result && getName().equals(other.getName());result = result && unknownFields.equals(other.unknownFields);return result;}@Overridepublic int hashCode() {if (memoizedHashCode != 0) {return memoizedHashCode;}int hash = 41;hash = (19 * hash) + getDescriptor().hashCode();hash = (37 * hash) + ID_FIELD_NUMBER;hash = (53 * hash) + getId();hash = (37 * hash) + NAME_FIELD_NUMBER;hash = (53 * hash) + getName().hashCode();hash = (29 * hash) + unknownFields.hashCode();memoizedHashCode = hash;return hash;}public static Student parseFrom(java.nio.ByteBuffer data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Student parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Student parseFrom(com.google.protobuf.ByteString data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Student parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Student parseFrom(byte[] data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Student parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Student parseFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static Student parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}public static Student parseDelimitedFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);}public static Student parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);}public static Student parseFrom(com.google.protobuf.CodedInputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static Student parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}@Overridepublic Builder newBuilderForType() { return newBuilder(); }public static Builder newBuilder() {return DEFAULT_INSTANCE.toBuilder();}public static Builder newBuilder(Student prototype) {return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);}@Overridepublic Builder toBuilder() {return this == DEFAULT_INSTANCE? new Builder() : new Builder().mergeFrom(this);}@Overrideprotected Builder newBuilderForType(BuilderParent parent) {Builder builder = new Builder(parent);return builder;}/*** Protobuf type {@code Student}*/public static final class Builder extendscom.google.protobuf.GeneratedMessageV3.Builder<Builder> implements// @@protoc_insertion_point(builder_implements:Student)StudentOrBuilder {public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return MyDataInfo.internal_static_Student_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return MyDataInfo.internal_static_Student_fieldAccessorTable.ensureFieldAccessorsInitialized(Student.class, Builder.class);}// Construct using com.jay.atguigu.netty.codec2.MyDataInfo.Student.newBuilder()private Builder() {maybeForceBuilderInitialization();}private Builder(BuilderParent parent) {super(parent);maybeForceBuilderInitialization();}private void maybeForceBuilderInitialization() {if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}}@Overridepublic Builder clear() {super.clear();id_ = 0;name_ = "";return this;}@Overridepublic com.google.protobuf.Descriptors.DescriptorgetDescriptorForType() {return MyDataInfo.internal_static_Student_descriptor;}@Overridepublic Student getDefaultInstanceForType() {return Student.getDefaultInstance();}@Overridepublic Student build() {Student result = buildPartial();if (!result.isInitialized()) {throw newUninitializedMessageException(result);}return result;}@Overridepublic Student buildPartial() {Student result = new Student(this);result.id_ = id_;result.name_ = name_;onBuilt();return result;}@Overridepublic Builder clone() {return (Builder) super.clone();}@Overridepublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.setField(field, value);}@Overridepublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {return (Builder) super.clearField(field);}@Overridepublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {return (Builder) super.clearOneof(oneof);}@Overridepublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index, Object value) {return (Builder) super.setRepeatedField(field, index, value);}@Overridepublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.addRepeatedField(field, value);}@Overridepublic Builder mergeFrom(com.google.protobuf.Message other) {if (other instanceof Student) {return mergeFrom((Student)other);} else {super.mergeFrom(other);return this;}}public Builder mergeFrom(Student other) {if (other == Student.getDefaultInstance()) return this;if (other.getId() != 0) {setId(other.getId());}if (!other.getName().isEmpty()) {name_ = other.name_;onChanged();}this.mergeUnknownFields(other.unknownFields);onChanged();return this;}@Overridepublic final boolean isInitialized() {return true;}@Overridepublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {Student parsedMessage = null;try {parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);} catch (com.google.protobuf.InvalidProtocolBufferException e) {parsedMessage = (Student) e.getUnfinishedMessage();throw e.unwrapIOException();} finally {if (parsedMessage != null) {mergeFrom(parsedMessage);}}return this;}private int id_ ;/*** <code>int32 id = 1;</code>*/public int getId() {return id_;}/*** <code>int32 id = 1;</code>*/public Builder setId(int value) {id_ = value;onChanged();return this;}/*** <code>int32 id = 1;</code>*/public Builder clearId() {id_ = 0;onChanged();return this;}private Object name_ = "";/*** <code>string name = 2;</code>*/public String getName() {Object ref = name_;if (!(ref instanceof String)) {com.google.protobuf.ByteString bs =(com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;} else {return (String) ref;}}/*** <code>string name = 2;</code>*/public com.google.protobuf.ByteStringgetNameBytes() {Object ref = name_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);name_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}/*** <code>string name = 2;</code>*/public Builder setName(String value) {if (value == null) {throw new NullPointerException();}name_ = value;onChanged();return this;}/*** <code>string name = 2;</code>*/public Builder clearName() {name_ = getDefaultInstance().getName();onChanged();return this;}/*** <code>string name = 2;</code>*/public Builder setNameBytes(com.google.protobuf.ByteString value) {if (value == null) {throw new NullPointerException();}checkByteStringIsUtf8(value);name_ = value;onChanged();return this;}@Overridepublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.setUnknownFieldsProto3(unknownFields);}@Overridepublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.mergeUnknownFields(unknownFields);}// @@protoc_insertion_point(builder_scope:Student)}// @@protoc_insertion_point(class_scope:Student)private static final Student DEFAULT_INSTANCE;static {DEFAULT_INSTANCE = new Student();}public static Student getDefaultInstance() {return DEFAULT_INSTANCE;}private static final com.google.protobuf.Parser<Student>PARSER = new com.google.protobuf.AbstractParser<Student>() {@Overridepublic Student parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return new Student(input, extensionRegistry);}};public static com.google.protobuf.Parser<Student> parser() {return PARSER;}@Overridepublic com.google.protobuf.Parser<Student> getParserForType() {return PARSER;}@Overridepublic Student getDefaultInstanceForType() {return DEFAULT_INSTANCE;}}public interface WorkerOrBuilder extends// @@protoc_insertion_point(interface_extends:Worker)com.google.protobuf.MessageOrBuilder {/*** <code>string name = 1;</code>*/String getName();/*** <code>string name = 1;</code>*/com.google.protobuf.ByteStringgetNameBytes();/*** <code>int32 age = 2;</code>*/int getAge();}/*** Protobuf type {@code Worker}*/public static final class Worker extendscom.google.protobuf.GeneratedMessageV3 implements// @@protoc_insertion_point(message_implements:Worker)WorkerOrBuilder {private static final long serialVersionUID = 0L;// Use Worker.newBuilder() to construct.private Worker(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {super(builder);}private Worker() {name_ = "";age_ = 0;}@Overridepublic final com.google.protobuf.UnknownFieldSetgetUnknownFields() {return this.unknownFields;}private Worker(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {this();if (extensionRegistry == null) {throw new NullPointerException();}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;case 10: {String s = input.readStringRequireUtf8();name_ = s;break;}case 16: {age_ = input.readInt32();break;}default: {if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {done = true;}break;}}}} catch (com.google.protobuf.InvalidProtocolBufferException e) {throw e.setUnfinishedMessage(this);} catch (java.io.IOException e) {throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);} finally {this.unknownFields = unknownFields.build();makeExtensionsImmutable();}}public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return MyDataInfo.internal_static_Worker_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return MyDataInfo.internal_static_Worker_fieldAccessorTable.ensureFieldAccessorsInitialized(Worker.class, Builder.class);}public static final int NAME_FIELD_NUMBER = 1;private volatile Object name_;/*** <code>string name = 1;</code>*/public String getName() {Object ref = name_;if (ref instanceof String) {return (String) ref;} else {com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;}}/*** <code>string name = 1;</code>*/public com.google.protobuf.ByteStringgetNameBytes() {Object ref = name_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);name_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}public static final int AGE_FIELD_NUMBER = 2;private int age_;/*** <code>int32 age = 2;</code>*/public int getAge() {return age_;}private byte memoizedIsInitialized = -1;@Overridepublic final boolean isInitialized() {byte isInitialized = memoizedIsInitialized;if (isInitialized == 1) return true;if (isInitialized == 0) return false;memoizedIsInitialized = 1;return true;}@Overridepublic void writeTo(com.google.protobuf.CodedOutputStream output)throws java.io.IOException {if (!getNameBytes().isEmpty()) {com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);}if (age_ != 0) {output.writeInt32(2, age_);}unknownFields.writeTo(output);}@Overridepublic int getSerializedSize() {int size = memoizedSize;if (size != -1) return size;size = 0;if (!getNameBytes().isEmpty()) {size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);}if (age_ != 0) {size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, age_);}size += unknownFields.getSerializedSize();memoizedSize = size;return size;}@Overridepublic boolean equals(final Object obj) {if (obj == this) {return true;}if (!(obj instanceof Worker)) {return super.equals(obj);}Worker other = (Worker) obj;boolean result = true;result = result && getName().equals(other.getName());result = result && (getAge()== other.getAge());result = result && unknownFields.equals(other.unknownFields);return result;}@Overridepublic int hashCode() {if (memoizedHashCode != 0) {return memoizedHashCode;}int hash = 41;hash = (19 * hash) + getDescriptor().hashCode();hash = (37 * hash) + NAME_FIELD_NUMBER;hash = (53 * hash) + getName().hashCode();hash = (37 * hash) + AGE_FIELD_NUMBER;hash = (53 * hash) + getAge();hash = (29 * hash) + unknownFields.hashCode();memoizedHashCode = hash;return hash;}public static Worker parseFrom(java.nio.ByteBuffer data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Worker parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Worker parseFrom(com.google.protobuf.ByteString data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Worker parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Worker parseFrom(byte[] data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Worker parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Worker parseFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static Worker parseFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}public static Worker parseDelimitedFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);}public static Worker parseDelimitedFrom(java.io.InputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);}public static Worker parseFrom(com.google.protobuf.CodedInputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static Worker parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}@Overridepublic Builder newBuilderForType() { return newBuilder(); }public static Builder newBuilder() {return DEFAULT_INSTANCE.toBuilder();}public static Builder newBuilder(Worker prototype) {return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);}@Overridepublic Builder toBuilder() {return this == DEFAULT_INSTANCE? new Builder() : new Builder().mergeFrom(this);}@Overrideprotected Builder newBuilderForType(BuilderParent parent) {Builder builder = new Builder(parent);return builder;}/*** Protobuf type {@code Worker}*/public static final class Builder extendscom.google.protobuf.GeneratedMessageV3.Builder<Builder> implements// @@protoc_insertion_point(builder_implements:Worker)WorkerOrBuilder {public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return MyDataInfo.internal_static_Worker_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return MyDataInfo.internal_static_Worker_fieldAccessorTable.ensureFieldAccessorsInitialized(Worker.class, Builder.class);}// Construct using com.jay.atguigu.netty.codec2.MyDataInfo.Worker.newBuilder()private Builder() {maybeForceBuilderInitialization();}private Builder(BuilderParent parent) {super(parent);maybeForceBuilderInitialization();}private void maybeForceBuilderInitialization() {if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}}@Overridepublic Builder clear() {super.clear();name_ = "";age_ = 0;return this;}@Overridepublic com.google.protobuf.Descriptors.DescriptorgetDescriptorForType() {return MyDataInfo.internal_static_Worker_descriptor;}@Overridepublic Worker getDefaultInstanceForType() {return Worker.getDefaultInstance();}@Overridepublic Worker build() {Worker result = buildPartial();if (!result.isInitialized()) {throw newUninitializedMessageException(result);}return result;}@Overridepublic Worker buildPartial() {Worker result = new Worker(this);result.name_ = name_;result.age_ = age_;onBuilt();return result;}@Overridepublic Builder clone() {return (Builder) super.clone();}@Overridepublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.setField(field, value);}@Overridepublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {return (Builder) super.clearField(field);}@Overridepublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {return (Builder) super.clearOneof(oneof);}@Overridepublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index, Object value) {return (Builder) super.setRepeatedField(field, index, value);}@Overridepublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.addRepeatedField(field, value);}@Overridepublic Builder mergeFrom(com.google.protobuf.Message other) {if (other instanceof Worker) {return mergeFrom((Worker)other);} else {super.mergeFrom(other);return this;}}public Builder mergeFrom(Worker other) {if (other == Worker.getDefaultInstance()) return this;if (!other.getName().isEmpty()) {name_ = other.name_;onChanged();}if (other.getAge() != 0) {setAge(other.getAge());}this.mergeUnknownFields(other.unknownFields);onChanged();return this;}@Overridepublic final boolean isInitialized() {return true;}@Overridepublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {Worker parsedMessage = null;try {parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);} catch (com.google.protobuf.InvalidProtocolBufferException e) {parsedMessage = (Worker) e.getUnfinishedMessage();throw e.unwrapIOException();} finally {if (parsedMessage != null) {mergeFrom(parsedMessage);}}return this;}private Object name_ = "";/*** <code>string name = 1;</code>*/public String getName() {Object ref = name_;if (!(ref instanceof String)) {com.google.protobuf.ByteString bs =(com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;} else {return (String) ref;}}/*** <code>string name = 1;</code>*/public com.google.protobuf.ByteStringgetNameBytes() {Object ref = name_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);name_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}/*** <code>string name = 1;</code>*/public Builder setName(String value) {if (value == null) {throw new NullPointerException();}name_ = value;onChanged();return this;}/*** <code>string name = 1;</code>*/public Builder clearName() {name_ = getDefaultInstance().getName();onChanged();return this;}/*** <code>string name = 1;</code>*/public Builder setNameBytes(com.google.protobuf.ByteString value) {if (value == null) {throw new NullPointerException();}checkByteStringIsUtf8(value);name_ = value;onChanged();return this;}private int age_ ;/*** <code>int32 age = 2;</code>*/public int getAge() {return age_;}/*** <code>int32 age = 2;</code>*/public Builder setAge(int value) {age_ = value;onChanged();return this;}/*** <code>int32 age = 2;</code>*/public Builder clearAge() {age_ = 0;onChanged();return this;}@Overridepublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.setUnknownFieldsProto3(unknownFields);}@Overridepublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.mergeUnknownFields(unknownFields);}// @@protoc_insertion_point(builder_scope:Worker)}// @@protoc_insertion_point(class_scope:Worker)private static final Worker DEFAULT_INSTANCE;static {DEFAULT_INSTANCE = new Worker();}public static Worker getDefaultInstance() {return DEFAULT_INSTANCE;}private static final com.google.protobuf.Parser<Worker>PARSER = new com.google.protobuf.AbstractParser<Worker>() {@Overridepublic Worker parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return new Worker(input, extensionRegistry);}};public static com.google.protobuf.Parser<Worker> parser() {return PARSER;}@Overridepublic com.google.protobuf.Parser<Worker> getParserForType() {return PARSER;}@Overridepublic Worker getDefaultInstanceForType() {return DEFAULT_INSTANCE;}}private static final com.google.protobuf.Descriptors.Descriptorinternal_static_MyMessage_descriptor;private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTableinternal_static_MyMessage_fieldAccessorTable;private static final com.google.protobuf.Descriptors.Descriptorinternal_static_Student_descriptor;private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTableinternal_static_Student_fieldAccessorTable;private static final com.google.protobuf.Descriptors.Descriptorinternal_static_Worker_descriptor;private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTableinternal_static_Worker_fieldAccessorTable;public static com.google.protobuf.Descriptors.FileDescriptorgetDescriptor() {return descriptor;}private static com.google.protobuf.Descriptors.FileDescriptordescriptor;static {String[] descriptorData = {"\n\014MyDate.proto\"\244\001\n\tMyMessage\022&\n\tdata_typ" +"e\030\001 \001(\0162\023.MyMessage.DataType\022\033\n\007student\030" +"\002 \001(\0132\010.StudentH\000\022\031\n\006worker\030\003 \001(\0132\007.Work" +"erH\000\"+\n\010DataType\022\017\n\013StudentType\020\000\022\016\n\nWor" +"kerType\020\001B\n\n\010dataBody\"#\n\007Student\022\n\n\002id\030\001" +" \001(\005\022\014\n\004name\030\002 \001(\t\"#\n\006Worker\022\014\n\004name\030\001 \001" +"(\t\022\013\n\003age\030\002 \001(\005B,\n\034com.jay.atguigu.netty" +".codec2B\nMyDataInfoH\001b\006proto3"};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;return null;}};com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData,new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);internal_static_MyMessage_descriptor =getDescriptor().getMessageTypes().get(0);internal_static_MyMessage_fieldAccessorTable = newcom.google.protobuf.GeneratedMessageV3.FieldAccessorTable(internal_static_MyMessage_descriptor,new String[] { "DataType", "Student", "Worker", "DataBody", });internal_static_Student_descriptor =getDescriptor().getMessageTypes().get(1);internal_static_Student_fieldAccessorTable = newcom.google.protobuf.GeneratedMessageV3.FieldAccessorTable(internal_static_Student_descriptor,new String[] { "Id", "Name", });internal_static_Worker_descriptor =getDescriptor().getMessageTypes().get(2);internal_static_Worker_fieldAccessorTable = newcom.google.protobuf.GeneratedMessageV3.FieldAccessorTable(internal_static_Worker_descriptor,new String[] { "Name", "Age", });}// @@protoc_insertion_point(outer_class_scope)
}
2.2 NettyServer.java
@Slf4j
public class NettyServer {public static void main(String[] args) {NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);NioEventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,128).childOption(ChannelOption.SO_KEEPALIVE,true).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("decoder",new ProtobufDecoder(MyDataInfo.MyMessage.getDefaultInstance()));pipeline.addLast(new NettyServerHandler());}});ChannelFuture channelFuture = serverBootstrap.bind(8000).sync();channelFuture.addListener(new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {if(future.isSuccess()){log.info("服务器监听 8000端口,成功");}else {log.info("服务器监听 8000端口,失败");}}});channelFuture.channel().closeFuture().sync();}catch (Exception e){e.printStackTrace();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}
2.3 NettyServerHandler.java
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception {//根据datatype判断MyDataInfo.MyMessage.DataType dataType = msg.getDataType();if(dataType == MyDataInfo.MyMessage.DataType.StudentType){MyDataInfo.Student student = msg.getStudent();log.info("学生id:{},学生姓名:{}",student.getId(),student.getName());}else if(dataType == MyDataInfo.MyMessage.DataType.WorkerType){MyDataInfo.Worker worker = msg.getWorker();log.info("工人姓名:{},工人年龄:{}",worker.getName(),worker.getAge());}else {log.error("传输的类型不正确");}}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(Unpooled.copiedBuffer("你好,客户端", CharsetUtil.UTF_8));}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}
2.4 NettyClient.java
public class NettyClient {public static void main(String[] args) {NioEventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("encoder",new ProtobufEncoder());pipeline.addLast(new NettyClientHandler());}});ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8000).sync();channelFuture.channel().closeFuture().sync();}catch (Exception e){e.printStackTrace();}finally {group.shutdownGracefully();}}
}
2.5 NettyClientHandler.java
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {//当通道准备就绪时,触发该方法@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//随机发送student或者workerint random = new Random().nextInt(3);MyDataInfo.MyMessage message = null;if( 0 == random ){message = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType).setStudent(MyDataInfo.Student.newBuilder().setId(1001).setName("学生甲").build()).build();}else{message = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.WorkerType).setWorker(MyDataInfo.Worker.newBuilder().setName("工人甲").setAge(30).build()).build();}ctx.writeAndFlush(message);}//当有数据读取时,触发该方法@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf) msg;log.info("服务器回复的消息是:{}",buf.toString(CharsetUtil.UTF_8));log.info("服务器的地址是:{}",ctx.channel().remoteAddress());}//发生异常时,触发该方法@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}
}
2.6 运行结果
多次执行NettyClient.java后,服务端运行如下: