Netty使用protobuf进行消息编解码代码示例
生活随笔
收集整理的這篇文章主要介紹了
Netty使用protobuf进行消息编解码代码示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
客戶端handler:
package cn.zhangxueliang.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 {@Overridepublic void channelActive(ChannelHandlerContext ctx) {BookMessage.Book book=BookMessage.Book.newBuilder().setId(1).setName("精通編程藝術").build();ctx.writeAndFlush(book);}}客戶端:
package cn.zhangxueliang.netty.codec;import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; 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.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder;public class NettyClient {public static void main(String[] args) throws Exception {EventLoopGroup group = new NioEventLoopGroup();Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel sc) {sc.pipeline().addLast("encoder",new ProtobufEncoder());sc.pipeline().addLast(new NettyClientHandler());}});// 啟動客戶端ChannelFuture cf = b.connect("127.0.0.1", 9999).sync(); // (5)// 等待連接關閉cf.channel().closeFuture().sync();} }服務端handler:
package cn.zhangxueliang.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 NettyServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {BookMessage.Book book=(BookMessage.Book)msg;System.out.println("客戶端發來數據:"+book.getName());}}服務端:
package cn.zhangxueliang.netty.codec;import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; 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 Exception{EventLoopGroup pGroup = new NioEventLoopGroup(); //線程組:用來處理網絡事件處理(接受客戶端連接)EventLoopGroup cGroup = new NioEventLoopGroup(); //線程組:用來進行網絡通訊讀寫ServerBootstrap b = new ServerBootstrap();b.group(pGroup, cGroup).channel(NioServerSocketChannel.class) //注冊服務端channel.option(ChannelOption.SO_BACKLOG, 128). childOption(ChannelOption.SO_KEEPALIVE, true).childHandler(new ChannelInitializer<SocketChannel>() {public void initChannel(SocketChannel sc) throws Exception {sc.pipeline().addLast("decoder",new ProtobufDecoder(BookMessage.Book.getDefaultInstance()));sc.pipeline().addLast(new NettyServerHandler());}});ChannelFuture cf = b.bind(9999).sync();System.out.println("......Server is Starting......");//釋放cf.channel().closeFuture().sync();pGroup.shutdownGracefully();cGroup.shutdownGracefully();} }Book.proto文件:
syntax = "proto3";option java_outer_classname = "BookMessage";message Book{int32 id = 1;string name = 2;}通過protobuf文件生成的java文件:
package cn.zhangxueliang.netty.codec;// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Book.protopublic final class BookMessage {private BookMessage() {}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 BookOrBuilder extends// @@protoc_insertion_point(interface_extends:Book)com.google.protobuf.MessageOrBuilder {/*** <code>int32 id = 1;</code>*/int getId();/*** <code>string name = 2;</code>*/String getName();/*** <code>string name = 2;</code>*/com.google.protobuf.ByteStringgetNameBytes();}/*** Protobuf type {@code Book}*/public static final class Book extendscom.google.protobuf.GeneratedMessageV3 implements// @@protoc_insertion_point(message_implements:Book)BookOrBuilder {private static final long serialVersionUID = 0L;// Use Book.newBuilder() to construct.private Book(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {super(builder);}private Book() {id_ = 0;name_ = "";}@Overridepublic final com.google.protobuf.UnknownFieldSetgetUnknownFields() {return this.unknownFields;}private Book(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {this();if (extensionRegistry == null) {throw new NullPointerException();}int mutable_bitField0_ = 0;com.google.protobuf.UnknownFieldSet.Builder unknownFields =com.google.protobuf.UnknownFieldSet.newBuilder();try {boolean done = false;while (!done) {int tag = input.readTag();switch (tag) {case 0:done = true;break;case 8: {id_ = input.readInt32();break;}case 18: {String s = input.readStringRequireUtf8();name_ = s;break;}default: {if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) {done = true;}break;}}}} catch (com.google.protobuf.InvalidProtocolBufferException e) {throw e.setUnfinishedMessage(this);} catch (java.io.IOException e) {throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);} finally {this.unknownFields = unknownFields.build();makeExtensionsImmutable();}}public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return BookMessage.internal_static_Book_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return BookMessage.internal_static_Book_fieldAccessorTable.ensureFieldAccessorsInitialized(Book.class, Builder.class);}public static final int ID_FIELD_NUMBER = 1;private int id_;/*** <code>int32 id = 1;</code>*/public int getId() {return id_;}public static final int NAME_FIELD_NUMBER = 2;private volatile Object name_;/*** <code>string name = 2;</code>*/public String getName() {Object ref = name_;if (ref instanceof String) {return (String) ref;} else {com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;}}/*** <code>string name = 2;</code>*/public com.google.protobuf.ByteStringgetNameBytes() {Object ref = name_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);name_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}private byte memoizedIsInitialized = -1;@Overridepublic final boolean isInitialized() {byte isInitialized = memoizedIsInitialized;if (isInitialized == 1) return true;if (isInitialized == 0) return false;memoizedIsInitialized = 1;return true;}@Overridepublic void writeTo(com.google.protobuf.CodedOutputStream output)throws java.io.IOException {if (id_ != 0) {output.writeInt32(1, id_);}if (!getNameBytes().isEmpty()) {com.google.protobuf.GeneratedMessageV3.writeString(output, 2, name_);}unknownFields.writeTo(output);}@Overridepublic int getSerializedSize() {int size = memoizedSize;if (size != -1) return size;size = 0;if (id_ != 0) {size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, id_);}if (!getNameBytes().isEmpty()) {size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, name_);}size += unknownFields.getSerializedSize();memoizedSize = size;return size;}@Overridepublic boolean equals(final Object obj) {if (obj == this) {return true;}if (!(obj instanceof Book)) {return super.equals(obj);}Book other = (Book) obj;boolean result = true;result = result && (getId()== other.getId());result = result && getName().equals(other.getName());result = result && unknownFields.equals(other.unknownFields);return result;}@Overridepublic int hashCode() {if (memoizedHashCode != 0) {return memoizedHashCode;}int hash = 41;hash = (19 * hash) + getDescriptor().hashCode();hash = (37 * hash) + ID_FIELD_NUMBER;hash = (53 * hash) + getId();hash = (37 * hash) + NAME_FIELD_NUMBER;hash = (53 * hash) + getName().hashCode();hash = (29 * hash) + unknownFields.hashCode();memoizedHashCode = hash;return hash;}public static Book parseFrom(java.nio.ByteBuffer data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Book parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Book parseFrom(com.google.protobuf.ByteString data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Book parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Book parseFrom(byte[] data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static Book parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static Book parseFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static Book 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 Book parseDelimitedFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);}public static Book 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 Book parseFrom(com.google.protobuf.CodedInputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static Book parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}@Overridepublic Builder newBuilderForType() { return newBuilder(); }public static Builder newBuilder() {return DEFAULT_INSTANCE.toBuilder();}public static Builder newBuilder(Book prototype) {return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);}@Overridepublic Builder toBuilder() {return this == DEFAULT_INSTANCE? new Builder() : new Builder().mergeFrom(this);}@Overrideprotected Builder newBuilderForType(BuilderParent parent) {Builder builder = new Builder(parent);return builder;}/*** Protobuf type {@code Book}*/public static final class Builder extendscom.google.protobuf.GeneratedMessageV3.Builder<Builder> implements// @@protoc_insertion_point(builder_implements:Book)BookOrBuilder {public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return BookMessage.internal_static_Book_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return BookMessage.internal_static_Book_fieldAccessorTable.ensureFieldAccessorsInitialized(Book.class, Builder.class);}// Construct using BookMessage.Book.newBuilder()private Builder() {maybeForceBuilderInitialization();}private Builder(BuilderParent parent) {super(parent);maybeForceBuilderInitialization();}private void maybeForceBuilderInitialization() {if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}}@Overridepublic Builder clear() {super.clear();id_ = 0;name_ = "";return this;}@Overridepublic com.google.protobuf.Descriptors.DescriptorgetDescriptorForType() {return BookMessage.internal_static_Book_descriptor;}@Overridepublic Book getDefaultInstanceForType() {return Book.getDefaultInstance();}@Overridepublic Book build() {Book result = buildPartial();if (!result.isInitialized()) {throw newUninitializedMessageException(result);}return result;}@Overridepublic Book buildPartial() {Book result = new Book(this);result.id_ = id_;result.name_ = name_;onBuilt();return result;}@Overridepublic Builder clone() {return (Builder) super.clone();}@Overridepublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.setField(field, value);}@Overridepublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {return (Builder) super.clearField(field);}@Overridepublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {return (Builder) super.clearOneof(oneof);}@Overridepublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index, Object value) {return (Builder) super.setRepeatedField(field, index, value);}@Overridepublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return (Builder) super.addRepeatedField(field, value);}@Overridepublic Builder mergeFrom(com.google.protobuf.Message other) {if (other instanceof Book) {return mergeFrom((Book)other);} else {super.mergeFrom(other);return this;}}public Builder mergeFrom(Book other) {if (other == Book.getDefaultInstance()) return this;if (other.getId() != 0) {setId(other.getId());}if (!other.getName().isEmpty()) {name_ = other.name_;onChanged();}this.mergeUnknownFields(other.unknownFields);onChanged();return this;}@Overridepublic final boolean isInitialized() {return true;}@Overridepublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {Book parsedMessage = null;try {parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);} catch (com.google.protobuf.InvalidProtocolBufferException e) {parsedMessage = (Book) e.getUnfinishedMessage();throw e.unwrapIOException();} finally {if (parsedMessage != null) {mergeFrom(parsedMessage);}}return this;}private int id_ ;/*** <code>int32 id = 1;</code>*/public int getId() {return id_;}/*** <code>int32 id = 1;</code>*/public Builder setId(int value) {id_ = value;onChanged();return this;}/*** <code>int32 id = 1;</code>*/public Builder clearId() {id_ = 0;onChanged();return this;}private Object name_ = "";/*** <code>string name = 2;</code>*/public String getName() {Object ref = name_;if (!(ref instanceof String)) {com.google.protobuf.ByteString bs =(com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;} else {return (String) ref;}}/*** <code>string name = 2;</code>*/public com.google.protobuf.ByteStringgetNameBytes() {Object ref = name_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);name_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}/*** <code>string name = 2;</code>*/public Builder setName(String value) {if (value == null) {throw new NullPointerException();}name_ = value;onChanged();return this;}/*** <code>string name = 2;</code>*/public Builder clearName() {name_ = getDefaultInstance().getName();onChanged();return this;}/*** <code>string name = 2;</code>*/public Builder setNameBytes(com.google.protobuf.ByteString value) {if (value == null) {throw new NullPointerException();}checkByteStringIsUtf8(value);name_ = value;onChanged();return this;}@Overridepublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.setUnknownFieldsProto3(unknownFields);}@Overridepublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.mergeUnknownFields(unknownFields);}// @@protoc_insertion_point(builder_scope:Book)}// @@protoc_insertion_point(class_scope:Book)private static final Book DEFAULT_INSTANCE;static {DEFAULT_INSTANCE = new Book();}public static Book getDefaultInstance() {return DEFAULT_INSTANCE;}private static final com.google.protobuf.Parser<Book>PARSER = new com.google.protobuf.AbstractParser<Book>() {@Overridepublic Book parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return new Book(input, extensionRegistry);}};public static com.google.protobuf.Parser<Book> parser() {return PARSER;}@Overridepublic com.google.protobuf.Parser<Book> getParserForType() {return PARSER;}@Overridepublic Book getDefaultInstanceForType() {return DEFAULT_INSTANCE;}}private static final com.google.protobuf.Descriptors.Descriptorinternal_static_Book_descriptor;private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTableinternal_static_Book_fieldAccessorTable;public static com.google.protobuf.Descriptors.FileDescriptorgetDescriptor() {return descriptor;}private static com.google.protobuf.Descriptors.FileDescriptordescriptor;static {String[] descriptorData = {"\n\nBook.proto\" \n\004Book\022\n\n\002id\030\001 \001(\005\022\014\n\004name" +"\030\002 \001(\tB\rB\013BookMessageb\006proto3"};com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) {descriptor = root;return null;}};com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData,new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);internal_static_Book_descriptor =getDescriptor().getMessageTypes().get(0);internal_static_Book_fieldAccessorTable = newcom.google.protobuf.GeneratedMessageV3.FieldAccessorTable(internal_static_Book_descriptor,new String[] { "Id", "Name", });}// @@protoc_insertion_point(outer_class_scope) }?
總結
以上是生活随笔為你收集整理的Netty使用protobuf进行消息编解码代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Netty网络聊天室完整代码实现
- 下一篇: Java代码示例: 使用reflecti