010-核心技术-netty-编码解码机制、protobuf、Netty入站出站机制、netty与log结合
一、概述
编写网络应用程序时,因为数据在网络中传输的都是二进制字节码数据,在发送数据时就需要编码,接收数据时就需要解码
codec(编解码器)的组成:decoder(解码器)和encoder(编码器)
encoder负责把业务数据转换成字节码数据,decoder负责把字节码数据转换成业务数据
1.1、Netty本身编解码机制与问题
1)Netty提供的编码器和解码器
StringEncoder、StringDecoder,对字符串数据进行编码解码
ObjectEncoder、ObjectDecoder,对java对象进行编码解码
2)问题分析
ObjectEncoder、ObjectDecoder可以用来实现POJO对象或各种业务对象的编码和解码,底层使用的时java序列化技术,存在如下问题:
无法跨语言、java序列化效率低、序列化后的体积太大,是二进制编码的5倍多、序列化性能低
引入新的方案:google的protobuf
1.2、Protobuf介绍和使用
是google开源项目,全称Google Protocol Buffers,是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。如数据存储、RPC等
pb是以message方式来管理数据的
支持跨平台、跨语言。
高性能、高可靠性
使用protobuf编译器能自动生成代码,Protobuf是将类的定义使用.proto文件进行描述。在idea中编写proto文件时,可以下载插件
通过protoc 编译器根据.proto自动生成java代码
1)基础类型
.proto类型 | java类型 | C++类型 | 备注 |
---|---|---|---|
double | double | double | |
float | float | float | |
int32 | int | int32 | 使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint32。 |
int64 | long | int64 | 使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint64。 |
unit32 | int[1] | unit32 | 总是4个字节。如果数值总是比总是比228大的话,这个类型会比uint32高效。 |
unit64 | long[1] | unit64 | 总是8个字节。如果数值总是比总是比256大的话,这个类型会比uint64高效。 |
sint32 | int | int32 | 使用可变长编码方式。有符号的整型值。编码时比通常的int32高效。 |
sint64 | long | int64 | 使用可变长编码方式。有符号的整型值。编码时比通常的int64高效。 |
fixed32 | int[1] | unit32 | |
fixed64 | long[1] | unit64 | 总是8个字节。如果数值总是比总是比256大的话,这个类型会比uint64高效。 |
sfixed32 | int | int32 | 总是4个字节。 |
sfixed64 | long | int64 | 总是8个字节。 |
bool | boolean | bool | |
string | String | string | 一个字符串必须是UTF-8编码或者7-bit ASCII编码的文本。 |
bytes | ByteString | string | 可能包含任意顺序的字节数据 |
2)特殊字段
英文 | 中文 | 备注 |
---|---|---|
enum | 枚举(数字从零开始) 作用是为字段指定某”预定义值序列” | enum Type {MAN = 0;WOMAN = 1; OTHER= 3;} |
message | 消息体 | message User{} |
repeated | 数组/集合 | repeated User users = 1 |
import | 导入定义 | import "protos/other_protos.proto" |
// | 注释 | //用于注释 |
extend | 扩展 | extend User {} |
package | 包名 | 相当于命名空间,用来防止不同消息类型的明明冲突 |
1.2.1、mac安装
brew install protobuf protobuf --version
1.2.2、编写proto文件
在/resources/proto下建立Student.proto文件,内容如下
syntax = "proto3"; option java_outer_classname = "StudentPOJO"; option java_package = "com.github.bjlhx15.netty.demo.netty.codec"; message Student{//会在StudentPOJO外部类生成一个内部类,是真实发送的数据 int32 id = 1 ;//1 属性序号 string name = 2; }
使用如下代码生成
protoc --java_out=../../java/ Student.proto
java代码如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Student.proto package com.github.bjlhx15.netty.demo.netty.codec; public final class StudentPOJO { private StudentPOJO() {} 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 StudentOrBuilder extends // @@protoc_insertion_point(interface_extends:Student) com.google.protobuf.MessageOrBuilder { /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return The id. */ int getId(); /** * <code>string name = 2;</code> * @return The name. */ java.lang.String getName(); /** * <code>string name = 2;</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); } /** * <pre> *会在StudentPOJO外部类生成一个内部类,是真实发送的数据 * </pre> * * Protobuf type {@code Student} */ public static final class Student extends com.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() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Student(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { 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 java.lang.NullPointerException(); } 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: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } default: { if (!parseUnknownField( 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.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.internal_static_Student_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.internal_static_Student_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student.class, com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private int id_; /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return The id. */ @java.lang.Override public int getId() { return id_; } public static final int NAME_FIELD_NUMBER = 2; private volatile java.lang.Object name_; /** * <code>string name = 2;</code> * @return The name. */ @java.lang.Override 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(); name_ = s; return s; } } /** * <code>string name = 2;</code> * @return The bytes for name. */ @java.lang.Override 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; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public 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); } @java.lang.Override public 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; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student)) { return super.equals(obj); } com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student other = (com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student) obj; if (getId() != other.getId()) return false; if (!getName() .equals(other.getName())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.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 com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.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 com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.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); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> *会在StudentPOJO外部类生成一个内部类,是真实发送的数据 * </pre> * * Protobuf type {@code Student} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Student) com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.StudentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.internal_static_Student_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.internal_static_Student_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student.class, com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student.Builder.class); } // Construct using com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); id_ = 0; name_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.internal_static_Student_descriptor; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student getDefaultInstanceForType() { return com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student.getDefaultInstance(); } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student build() { com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student buildPartial() { com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student result = new com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student(this); result.id_ = id_; result.name_ = name_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student) { return mergeFrom((com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student other) { if (other == com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.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; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int id_ ; /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return The id. */ @java.lang.Override public int getId() { return id_; } /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @param value The id to set. * @return This builder for chaining. */ public Builder setId(int value) { id_ = value; onChanged(); return this; } /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return This builder for chaining. */ public Builder clearId() { id_ = 0; onChanged(); return this; } private java.lang.Object name_ = ""; /** * <code>string name = 2;</code> * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string name = 2;</code> * @return The bytes for name. */ 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>string name = 2;</code> * @param value The name to set. * @return This builder for chaining. */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <code>string name = 2;</code> * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>string name = 2;</code> * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student(); } public static com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Student> PARSER = new com.google.protobuf.AbstractParser<Student>() { @java.lang.Override public 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; } @java.lang.Override public com.google.protobuf.Parser<Student> getParserForType() { return PARSER; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec.StudentPOJO.Student getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_Student_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Student_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\rStudent.proto\"#\n\007Student\022\n\n\002id\030\001 \001(\005\022\014" + "\n\004name\030\002 \001(\tB8\n)com.github.bjlhx15.netty" + ".demo.netty.codecB\013StudentPOJOb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_Student_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Student_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Student_descriptor, new java.lang.String[] { "Id", "Name", }); } // @@protoc_insertion_point(outer_class_scope) }
1.2.3、java使用
针对单一类型如下
服务端
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.github.bjlhx15.netty.demo.netty.codec; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; public class NettyServer { public static void main(String[] args) throws InterruptedException { // 创建 bossGroup 和 workerGroup // bossGroup 处理accept,workerGroup处理业务 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { //创建服务端的启动对象,配置参数 ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup)//设置两个线程组 .channel(NioServerSocketChannel.class)//使用NioSocketChannel作为服务器的通道实现 .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列得到的连接个数 .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动连接状态 .childHandler(new ChannelInitializer<SocketChannel>() { // 创建一个通道初始化 // 给Pipeline设置处理器 @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); // 需要指定对那种对象解码 pipeline.addLast("decoder", new ProtobufDecoder(StudentPOJO.Student.getDefaultInstance())); pipeline.addLast(new NettyServerHandler()); } }); System.out.println("……服务器 is ready。"); //绑定一个端口并且同步,生成一个ChannelFuture对象 //启动服务器(并绑定端口) ChannelFuture cf = bootstrap.bind(6668).sync(); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (cf.isSuccess()) { System.out.println("监听端口 6668 成功"); } else { System.out.println("监听端口 6668 失败"); } } }); //对关闭通道进行监听 cf.channel().closeFuture().sync(); } finally { // 优雅的关闭 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
服务端handler
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.github.bjlhx15.netty.demo.netty.codec; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.util.CharsetUtil; /** * 1、自定义一个handler,继承ChannelInboundHandlerAdapter */ //public class NettyServerHandler extends ChannelInboundHandlerAdapter { public class NettyServerHandler extends SimpleChannelInboundHandler<StudentPOJO.Student> { //读取实际数据 //ChannelHandlerContext 上下文对象,含有管道pipeline、通道channel,地址 //Object msg:客户端数据,默认Object // @Override // public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // StudentPOJO.Student student = (StudentPOJO.Student) msg; // System.out.println("客户端发送的数据" + student.toString()); // } @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, StudentPOJO.Student student) throws Exception { System.out.println("客户端发送的数据" + student.toString()); } //数据读取完毕 @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // writeAndFlush 是 write和 flush // 将数据写入到缓存,并刷新 // 将写入数据进行编码 ctx.writeAndFlush(Unpooled.copiedBuffer("hello client", CharsetUtil.UTF_8)); } //处理异常一般关闭通道 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
客户端
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.github.bjlhx15.netty.demo.netty.codec; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.protobuf.ProtobufEncoder; public class NettyClient { public static void main(String[] args) throws InterruptedException { // 客户端需要一个事件循环组 EventLoopGroup group = new NioEventLoopGroup(); try { // 创建客户端启动对象 // 不是ServerBootstrap 而是 Bootstrap Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group)//设置线程组 .channel(NioSocketChannel.class)//设置客户端通道的实现类(反射) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("encoder", new ProtobufEncoder()); pipeline.addLast(new NettyClientHandler());//加入自己的处理器 } }); System.out.println("客户端 ok"); // 启动客户端去连接服务器 ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync(); // 关闭通道进行监听, channelFuture.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } }
客户端handler
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.github.bjlhx15.netty.demo.netty.codec; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; public class NettyClientHandler extends ChannelInboundHandlerAdapter { // 当通道就绪就会触发该方法 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("client ctx:" + ctx); StudentPOJO.Student student = StudentPOJO.Student.newBuilder() .setId(4).setName("张三").build(); ctx.writeAndFlush(student); } //当通道有读取事件时,会触发 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf byteBuf = (ByteBuf) msg; System.out.println("server response:" + byteBuf.toString(CharsetUtil.UTF_8)); System.out.println("server address:" + ctx.channel().remoteAddress()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
问题:多种类型开发复杂
1.2.4、传输多种类型
编写proto文件
syntax = "proto3"; option optimize_for = SPEED;//加快解析 option java_package = "com.github.bjlhx15.netty.demo.netty.codec2"; option java_outer_classname = "ProtoDataEntity"; //protobuf 可以使用message管理其他message message MyMessage{ //定义一个枚举 enum DataType{ StudentType = 0; //proto3从0开始 WorkerType = 1; } //用data_type来标识传的时哪一个枚举 DataType data_type = 1; //表示每次枚举类型最多只能出现其中的一个,节省空间 oneof dataBody{ Student student = 2; Worker worker = 3; } } message Student{//会在StudentPOJO外部类生成一个内部类,是真实发送的数据 int32 id = 1 ;//1 属性序号 string name = 2; } message Worker{ string name = 1; int32 id = 2 ;//1 属性序号 }
使用如下代码生成
protoc --java_out=../../java/ Student2.proto
生成的java代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Student2.proto package com.github.bjlhx15.netty.demo.netty.codec2; public final class ProtoDataEntity { private ProtoDataEntity() {} 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> * @return The enum numeric value on the wire for dataType. */ int getDataTypeValue(); /** * <pre> *用data_type来标识传的时哪一个枚举 * </pre> * * <code>.MyMessage.DataType data_type = 1;</code> * @return The dataType. */ com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType getDataType(); /** * <code>.Student student = 2;</code> * @return Whether the student field is set. */ boolean hasStudent(); /** * <code>.Student student = 2;</code> * @return The student. */ com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student getStudent(); /** * <code>.Student student = 2;</code> */ com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder getStudentOrBuilder(); /** * <code>.Worker worker = 3;</code> * @return Whether the worker field is set. */ boolean hasWorker(); /** * <code>.Worker worker = 3;</code> * @return The worker. */ com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker getWorker(); /** * <code>.Worker worker = 3;</code> */ com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder getWorkerOrBuilder(); public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataBodyCase getDataBodyCase(); } /** * Protobuf type {@code MyMessage} */ public static final class MyMessage extends com.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; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MyMessage(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { 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 java.lang.NullPointerException(); } 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: { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder subBuilder = null; if (dataBodyCase_ == 2) { subBuilder = ((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_).toBuilder(); } dataBody_ = input.readMessage(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_); dataBody_ = subBuilder.buildPartial(); } dataBodyCase_ = 2; break; } case 26: { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder subBuilder = null; if (dataBodyCase_ == 3) { subBuilder = ((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_).toBuilder(); } dataBody_ = input.readMessage(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_); dataBody_ = subBuilder.buildPartial(); } dataBodyCase_ = 3; break; } default: { if (!parseUnknownField( 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.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_MyMessage_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_MyMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.class, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.Builder.class); } /** * <pre> *定义一个枚举 * </pre> * * Protobuf enum {@code MyMessage.DataType} */ public enum DataType implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> *proto3从0开始 * </pre> * * <code>StudentType = 0;</code> */ StudentType(0), /** * <code>WorkerType = 1;</code> */ WorkerType(1), UNRECOGNIZED(-1), ; /** * <pre> *proto3从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 java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static DataType valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire 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.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 java.lang.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 java.lang.Object dataBody_; public enum DataBodyCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { STUDENT(2), WORKER(3), DATABODY_NOT_SET(0); private final int value; private DataBodyCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public 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 DataBodyCase getDataBodyCase() { 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> * @return The enum numeric value on the wire for dataType. */ @java.lang.Override public int getDataTypeValue() { return dataType_; } /** * <pre> *用data_type来标识传的时哪一个枚举 * </pre> * * <code>.MyMessage.DataType data_type = 1;</code> * @return The dataType. */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType getDataType() { @SuppressWarnings("deprecation") com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType result = com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType.valueOf(dataType_); return result == null ? com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType.UNRECOGNIZED : result; } public static final int STUDENT_FIELD_NUMBER = 2; /** * <code>.Student student = 2;</code> * @return Whether the student field is set. */ @java.lang.Override public boolean hasStudent() { return dataBodyCase_ == 2; } /** * <code>.Student student = 2;</code> * @return The student. */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student getStudent() { if (dataBodyCase_ == 2) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } /** * <code>.Student student = 2;</code> */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder getStudentOrBuilder() { if (dataBodyCase_ == 2) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } public static final int WORKER_FIELD_NUMBER = 3; /** * <code>.Worker worker = 3;</code> * @return Whether the worker field is set. */ @java.lang.Override public boolean hasWorker() { return dataBodyCase_ == 3; } /** * <code>.Worker worker = 3;</code> * @return The worker. */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker getWorker() { if (dataBodyCase_ == 3) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } /** * <code>.Worker worker = 3;</code> */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder getWorkerOrBuilder() { if (dataBodyCase_ == 3) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (dataType_ != com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType.StudentType.getNumber()) { output.writeEnum(1, dataType_); } if (dataBodyCase_ == 2) { output.writeMessage(2, (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_); } if (dataBodyCase_ == 3) { output.writeMessage(3, (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (dataType_ != com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType.StudentType.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, dataType_); } if (dataBodyCase_ == 2) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_); } if (dataBodyCase_ == 3) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage)) { return super.equals(obj); } com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage other = (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage) obj; if (dataType_ != other.dataType_) return false; if (!getDataBodyCase().equals(other.getDataBodyCase())) return false; switch (dataBodyCase_) { case 2: if (!getStudent() .equals(other.getStudent())) return false; break; case 3: if (!getWorker() .equals(other.getWorker())) return false; break; case 0: default: } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code MyMessage} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:MyMessage) com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_MyMessage_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_MyMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.class, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.Builder.class); } // Construct using com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); dataType_ = 0; dataBodyCase_ = 0; dataBody_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_MyMessage_descriptor; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage getDefaultInstanceForType() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.getDefaultInstance(); } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage build() { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage buildPartial() { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage result = new com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage) { return mergeFrom((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage other) { if (other == com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int dataBodyCase_ = 0; private java.lang.Object dataBody_; public DataBodyCase getDataBodyCase() { 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> * @return The enum numeric value on the wire for dataType. */ @java.lang.Override public int getDataTypeValue() { return dataType_; } /** * <pre> *用data_type来标识传的时哪一个枚举 * </pre> * * <code>.MyMessage.DataType data_type = 1;</code> * @param value The enum numeric value on the wire for dataType to set. * @return This builder for chaining. */ public Builder setDataTypeValue(int value) { dataType_ = value; onChanged(); return this; } /** * <pre> *用data_type来标识传的时哪一个枚举 * </pre> * * <code>.MyMessage.DataType data_type = 1;</code> * @return The dataType. */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType getDataType() { @SuppressWarnings("deprecation") com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType result = com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType.valueOf(dataType_); return result == null ? com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.DataType.UNRECOGNIZED : result; } /** * <pre> *用data_type来标识传的时哪一个枚举 * </pre> * * <code>.MyMessage.DataType data_type = 1;</code> * @param value The dataType to set. * @return This builder for chaining. */ public Builder setDataType(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage.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> * @return This builder for chaining. */ public Builder clearDataType() { dataType_ = 0; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder> studentBuilder_; /** * <code>.Student student = 2;</code> * @return Whether the student field is set. */ @java.lang.Override public boolean hasStudent() { return dataBodyCase_ == 2; } /** * <code>.Student student = 2;</code> * @return The student. */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student getStudent() { if (studentBuilder_ == null) { if (dataBodyCase_ == 2) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } else { if (dataBodyCase_ == 2) { return studentBuilder_.getMessage(); } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } } /** * <code>.Student student = 2;</code> */ public Builder setStudent(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student value) { if (studentBuilder_ == null) { if (dataBodyCase_ == 2 && dataBody_ != com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance()) { dataBody_ = com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.newBuilder((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder getStudentBuilder() { return getStudentFieldBuilder().getBuilder(); } /** * <code>.Student student = 2;</code> */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder getStudentOrBuilder() { if ((dataBodyCase_ == 2) && (studentBuilder_ != null)) { return studentBuilder_.getMessageOrBuilder(); } else { if (dataBodyCase_ == 2) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } } /** * <code>.Student student = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder> getStudentFieldBuilder() { if (studentBuilder_ == null) { if (!(dataBodyCase_ == 2)) { dataBody_ = com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } studentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder>( (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) dataBody_, getParentForChildren(), isClean()); dataBody_ = null; } dataBodyCase_ = 2; onChanged();; return studentBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder> workerBuilder_; /** * <code>.Worker worker = 3;</code> * @return Whether the worker field is set. */ @java.lang.Override public boolean hasWorker() { return dataBodyCase_ == 3; } /** * <code>.Worker worker = 3;</code> * @return The worker. */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker getWorker() { if (workerBuilder_ == null) { if (dataBodyCase_ == 3) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } else { if (dataBodyCase_ == 3) { return workerBuilder_.getMessage(); } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } } /** * <code>.Worker worker = 3;</code> */ public Builder setWorker(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker value) { if (workerBuilder_ == null) { if (dataBodyCase_ == 3 && dataBody_ != com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance()) { dataBody_ = com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.newBuilder((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder getWorkerBuilder() { return getWorkerFieldBuilder().getBuilder(); } /** * <code>.Worker worker = 3;</code> */ @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder getWorkerOrBuilder() { if ((dataBodyCase_ == 3) && (workerBuilder_ != null)) { return workerBuilder_.getMessageOrBuilder(); } else { if (dataBodyCase_ == 3) { return (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_; } return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } } /** * <code>.Worker worker = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder> getWorkerFieldBuilder() { if (workerBuilder_ == null) { if (!(dataBodyCase_ == 3)) { dataBody_ = com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } workerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder>( (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) dataBody_, getParentForChildren(), isClean()); dataBody_ = null; } dataBodyCase_ = 3; onChanged();; return workerBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage(); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MyMessage> PARSER = new com.google.protobuf.AbstractParser<MyMessage>() { @java.lang.Override public 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; } @java.lang.Override public com.google.protobuf.Parser<MyMessage> getParserForType() { return PARSER; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.MyMessage getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface StudentOrBuilder extends // @@protoc_insertion_point(interface_extends:Student) com.google.protobuf.MessageOrBuilder { /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return The id. */ int getId(); /** * <code>string name = 2;</code> * @return The name. */ java.lang.String getName(); /** * <code>string name = 2;</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); } /** * <pre> *会在StudentPOJO外部类生成一个内部类,是真实发送的数据 * </pre> * * Protobuf type {@code Student} */ public static final class Student extends com.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() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Student(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { 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 java.lang.NullPointerException(); } 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: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } default: { if (!parseUnknownField( 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.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Student_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Student_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.class, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private int id_; /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return The id. */ @java.lang.Override public int getId() { return id_; } public static final int NAME_FIELD_NUMBER = 2; private volatile java.lang.Object name_; /** * <code>string name = 2;</code> * @return The name. */ @java.lang.Override 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(); name_ = s; return s; } } /** * <code>string name = 2;</code> * @return The bytes for name. */ @java.lang.Override 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; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public 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); } @java.lang.Override public 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; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student)) { return super.equals(obj); } com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student other = (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) obj; if (getId() != other.getId()) return false; if (!getName() .equals(other.getName())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> *会在StudentPOJO外部类生成一个内部类,是真实发送的数据 * </pre> * * Protobuf type {@code Student} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Student) com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.StudentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Student_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Student_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.class, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.Builder.class); } // Construct using com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); id_ = 0; name_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Student_descriptor; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student getDefaultInstanceForType() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student.getDefaultInstance(); } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student build() { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student buildPartial() { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student result = new com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student(this); result.id_ = id_; result.name_ = name_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) { return mergeFrom((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student other) { if (other == com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int id_ ; /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return The id. */ @java.lang.Override public int getId() { return id_; } /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @param value The id to set. * @return This builder for chaining. */ public Builder setId(int value) { id_ = value; onChanged(); return this; } /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 1;</code> * @return This builder for chaining. */ public Builder clearId() { id_ = 0; onChanged(); return this; } private java.lang.Object name_ = ""; /** * <code>string name = 2;</code> * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string name = 2;</code> * @return The bytes for name. */ 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>string name = 2;</code> * @param value The name to set. * @return This builder for chaining. */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <code>string name = 2;</code> * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>string name = 2;</code> * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student(); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Student> PARSER = new com.google.protobuf.AbstractParser<Student>() { @java.lang.Override public 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; } @java.lang.Override public com.google.protobuf.Parser<Student> getParserForType() { return PARSER; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Student getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface WorkerOrBuilder extends // @@protoc_insertion_point(interface_extends:Worker) com.google.protobuf.MessageOrBuilder { /** * <code>string name = 1;</code> * @return The name. */ java.lang.String getName(); /** * <code>string name = 1;</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 2;</code> * @return The id. */ int getId(); } /** * Protobuf type {@code Worker} */ public static final class Worker extends com.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_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Worker(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { 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 java.lang.NullPointerException(); } 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: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 16: { id_ = input.readInt32(); break; } default: { if (!parseUnknownField( 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.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Worker_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Worker_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.class, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <code>string name = 1;</code> * @return The name. */ @java.lang.Override 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(); name_ = s; return s; } } /** * <code>string name = 1;</code> * @return The bytes for name. */ @java.lang.Override 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; } } public static final int ID_FIELD_NUMBER = 2; private int id_; /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 2;</code> * @return The id. */ @java.lang.Override public int getId() { return id_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (id_ != 0) { output.writeInt32(2, id_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (id_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, id_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker)) { return super.equals(obj); } com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker other = (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) obj; if (!getName() .equals(other.getName())) return false; if (getId() != other.getId()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public 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) + ID_FIELD_NUMBER; hash = (53 * hash) + getId(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.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); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Worker} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Worker) com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.WorkerOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Worker_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Worker_fieldAccessorTable .ensureFieldAccessorsInitialized( com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.class, com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.Builder.class); } // Construct using com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; id_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.internal_static_Worker_descriptor; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker getDefaultInstanceForType() { return com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance(); } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker build() { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker buildPartial() { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker result = new com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker(this); result.name_ = name_; result.id_ = id_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) { return mergeFrom((com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker other) { if (other == com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (other.getId() != 0) { setId(other.getId()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object name_ = ""; /** * <code>string name = 1;</code> * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string name = 1;</code> * @return The bytes for name. */ 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>string name = 1;</code> * @param value The name to set. * @return This builder for chaining. */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <code>string name = 1;</code> * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>string name = 1;</code> * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private int id_ ; /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 2;</code> * @return The id. */ @java.lang.Override public int getId() { return id_; } /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 2;</code> * @param value The id to set. * @return This builder for chaining. */ public Builder setId(int value) { id_ = value; onChanged(); return this; } /** * <pre> *1 属性序号 * </pre> * * <code>int32 id = 2;</code> * @return This builder for chaining. */ public Builder clearId() { id_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public 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 com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker(); } public static com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Worker> PARSER = new com.google.protobuf.AbstractParser<Worker>() { @java.lang.Override public 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; } @java.lang.Override public com.google.protobuf.Parser<Worker> getParserForType() { return PARSER; } @java.lang.Override public com.github.bjlhx15.netty.demo.netty.codec2.ProtoDataEntity.Worker getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_MyMessage_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MyMessage_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_Student_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Student_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_Worker_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Worker_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\016Student2.proto\"\244\001\n\tMyMessage\022&\n\tdata_t" + "ype\030\001 \001(\0162\023.MyMessage.DataType\022\033\n\007studen" + "t\030\002 \001(\0132\010.StudentH\000\022\031\n\006worker\030\003 \001(\0132\007.Wo" + "rkerH\000\"+\n\010DataType\022\017\n\013StudentType\020\000\022\016\n\nW" + "orkerType\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\n\n\002id\030\002 \001(\005B?\n*com.github.bjlhx15.n" + "etty.demo.netty.codec2B\017ProtoDataEntityH" + "\001b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }); internal_static_MyMessage_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_MyMessage_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_MyMessage_descriptor, new java.lang.String[] { "DataType", "Student", "Worker", "DataBody", }); internal_static_Student_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_Student_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Student_descriptor, new java.lang.String[] { "Id", "Name", }); internal_static_Worker_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_Worker_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_Worker_descriptor, new java.lang.String[] { "Name", "Id", }); } // @@protoc_insertion_point(outer_class_scope) }
客户端发送代码整体如上,修改如下:
public void channelActive(ChannelHandlerContext ctx) throws Exception { int random = new Random().nextInt(3); ProtoDataEntity.MyMessage myMessage=null; if(0==random){ myMessage=ProtoDataEntity.MyMessage.newBuilder() .setDataType(ProtoDataEntity.MyMessage.DataType.StudentType) .setStudent(ProtoDataEntity.Student.newBuilder().setId(3).build()) .build(); }else{ myMessage=ProtoDataEntity.MyMessage.newBuilder() .setDataType(ProtoDataEntity.MyMessage.DataType.WorkerType) .setWorker(ProtoDataEntity.Worker.newBuilder().setId(30).build()) .build(); } }
服务端接收
@Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProtoDataEntity.MyMessage msg) throws Exception { switch (msg.getDataType()) { case StudentType: System.out.println("学生:"+msg.getStudent().toString()); break; case WorkerType: System.out.println("工人:"+msg.getWorker().toString()); break; case UNRECOGNIZED: System.out.println("类型不对:"+msg.toString()); break; } }
二、Netty入站出站机制
Netty是基于组件设计的,主要组件有Channel、EventLoop、ChannelFuture、ChannelHandler、ChannelPipeline等
ChannelHandler充当了处理入站和出站数据的应用程序逻辑容器。如,实现ChannelInboundHandler接口(或ChannelInboundhandlerAdapter)就可以接收入站事件和数据,以及冲刷数据,业务通常卸载一个或多个ChannelInboundHandler中。ChannelOutboundHandler原理一样。处理出站数据。
2.1、ChannelPipeline提供了ChannelHandler链的容器。
数据类型不一致,就会跳过对应的handler处理器;在进行编解码时,需要判断缓存去ByteBuf的数据是否足够,否则接收到的结果会与期望不一致
2.1.1、编解码器
当Netty发送或者接收一个消息的时候,就会发生一次数据转换。入站消息会被解码;从字节转换为另一种格式(比如java对象);如果是出站,它会被编码程字节
Netty提供了一系列实用的编解码器,它们都实现了ChannelInboundHandler或者channelOutboundHandler接口。在这些类中,channelRead方法已经被重写了。他将调用由解码器所提供的decode()方法进行解码,并将已经解码的字节转发给ChannelPipeline中的下一个ChannelInboundHandler。
1)ByteToMessageDecoder解码器
由于不可能知道远程节点是否会一次性发送一个完整额信息,tcp有可能出现粘包拆包的问题,直到它准备好被处理。
实例:
public class ToIntegerDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() >= 4) { out.add(in.readInt()); } } }
每次入站从ByteBuffer中读取4字节,将其解码为一个int,然后将它添加到下一list中,当没有更多元素添加可以添加到该LIst中时,他的内容将会被发送给下一个ChannelInboundHandler。
2.1.2、编解码图示说明
实例:
2.1.3、其他编解码器
1)解码器-ReplayingDecoder
public abstract class ReplayingDecoder<S> extends ByteToMessageDecoder
ReplayingDecoder扩展了ByteToMessageDecoder,使用这个类不必调用readableBytes()方法,参数S指定了用户状态类型,其中Void代表不需要状态管理
使用比较方便,有些缺点:不是所有的ByteBuf操作都被支持,如果调用了一个不被支持的方法,将会抛出一个UnsupportedOperationException。某些情况下慢于ByteToMessageDecoder,如网络缓慢并且消息格式复杂,消息将被拆成了多个碎片,速度变慢。
2)LineBasedFrameDecoder
使用行尾控制字符(\n或\r\n)作为分隔符来解析数据
3)DelimiterBasedFrameDecoder
使用自定义字符作为消息的分隔符
4)HttpObjectDecoder
一个http数据的解码包
5)LengthFieldBasedFrameDecoder
通过指定长度来标识整包消息,这样就能自动处理黏包和半包消息
6)其他
Zlib等
三、netty与log结合
3.1、Log4j整合netty
pom
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency>
添加log4j.properties
log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%p] %C{1} - %m%n
定时