Netty对Protocol Buffer多协议的支持(八)

一.背景

  在上篇博文中笔者已经用代码演示了如何在netty中使用Protocol Buffer,然而细心的用户可能会发现一个明显的不足之处就是,我们的Handler只能处理一种特定的类型,而我们的项目中又不可能只有一种类型,那么这个问题该怎么解决了?多的不说,笔者直接上代码。

二.代码实现

2.1 message的编写

syntax = "proto2";
package com.rsy.netty.protobuf;
option java_package = "com.rsy.netty.protobuf";
option java_outer_classname = "DataInfo";message Datas{enum DataType {personType = 1;dogType = 2;}    required DataType data_type = 1;oneof type_data{Person person = 2;Dog dog = 3;}
}message Person{required int32 id = 1;optional string name = 2;enum Gender {male = 1;female = 2;}optional Gender gender = 3;
}message Dog {required float height = 1;optional string color = 2;optional int64 age = 3;
}

2.2 生成Java代码,在此不再赘述。

2.3 服务端启动代码

public class ServerTest {public static void main(String[] args) throws Exception {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try{ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ServerChannelInitilizer());ChannelFuture channelFuture = serverBootstrap.bind(8989).sync();channelFuture.channel().closeFuture().sync();}finally{bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}

2.4 服务端通道初始化代码

public class ServerChannelInitilizer extends ChannelInitializer<SocketChannel>{@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("protobufVarint32FrameDecoder", new ProtobufVarint32FrameDecoder());pipeline.addLast("protobufDecoder", new ProtobufDecoder(DataInfo.Datas.getDefaultInstance()));pipeline.addLast("protobufVarint32LengthFieldPrepender", new ProtobufVarint32LengthFieldPrepender());pipeline.addLast("protobufEncoder", new ProtobufEncoder());pipeline.addLast("serverHandler", new ServerHandler());}
}

2.5 服务端Handler代码

public class ServerHandler extends SimpleChannelInboundHandler<DataInfo.Datas>{@Overrideprotected void channelRead0(ChannelHandlerContext ctx, DataInfo.Datas msg) throws Exception {/*** 因为最先写过来的是Person*/DataInfo.Person p = msg.getPerson();System.out.println(msg.getDataType().toString());System.out.println(p.getId());System.out.println(p.getGender().toString());System.out.println(p.getName());DataInfo.Datas data = DataInfo.Datas.newBuilder().setDataType(DataType.dogType).setDog(DataInfo.Dog.newBuilder().setAge(23).setColor("红色").setHeight(3.5f)).build();ctx.writeAndFlush(data);}
}

2.6 客户端启动代码

public class ClientTest {public static void main(String[] args) throws Exception {EventLoopGroup eventLoopGroup = new NioEventLoopGroup();try{Bootstrap bootstrap = new Bootstrap();bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ClientChannelInitializer());ChannelFuture channelFuture = bootstrap.connect("localhost", 8989).sync();channelFuture.channel().closeFuture().sync();}finally{eventLoopGroup.shutdownGracefully();}}
}

2.7 客户端通道初始化代码

public class ClientChannelInitializer extends ChannelInitializer<SocketChannel>{@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("protobufVarint32FrameDecoder", new ProtobufVarint32FrameDecoder());pipeline.addLast("protobufDecoder", new ProtobufDecoder(DataInfo.Datas.getDefaultInstance()));pipeline.addLast("protobufVarint32LengthFieldPrepender", new ProtobufVarint32LengthFieldPrepender());pipeline.addLast("protobufEncoder", new ProtobufEncoder());pipeline.addLast("clientHandler", new ClientHandler());}
}

2.8 客户端Handler处理代码

public class ClientHandler extends SimpleChannelInboundHandler<DataInfo.Datas>{@Overrideprotected void channelRead0(ChannelHandlerContext ctx, DataInfo.Datas msg) throws Exception {/*** 服务端写回来的是dog*/DataInfo.Dog dog = msg.getDog();System.out.println(msg.getDataType().toString());System.out.println(dog.getAge());System.out.println(dog.getColor());System.out.println(dog.getHeight());}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {DataInfo.Datas data = DataInfo.Datas.newBuilder().setDataType(DataType.personType).setPerson(DataInfo.Person.newBuilder().setId(23).setGender(Gender.female).setName("zhangsan")).build();ctx.writeAndFlush(data);}
}

三.运行

  运行服务端启动代码,再运行客户端启动代码。

转载于:https://www.cnblogs.com/miller-zou/p/7045711.html

Netty对Protocol Buffer多协议的支持(八)相关推荐

  1. gRPC in ASP.NET Core 3.x -- Protocol Buffer, Go语言的例子(上)

    前两篇文章半年前写的: gRPC in ASP.NET Core 3.0 -- Protocol Buffer(1), gRPC in ASP.NET Core 3.0 -- Protocol Buf ...

  2. 通信协议之Protocol buffer(Java篇)

    之前一直习惯用json进行数据的传输,觉得很方便.来到新公司后发现同事们用的更多的的协议都不是json,而是Protocol buffer.这个东西之前没有听说过,不明白同事们为什么放弃好好的json ...

  3. Protocol Buffer技术详解(语言规范)

     该系列Blog的内容主体主要源自于Protocol Buffer的官方文档,而代码示例则抽取于当前正在开发的一个公司内部项目的Demo.这样做的目的主要在于不仅可以保持Google文档的良好风格 ...

  4. Netty实战 IM即时通讯系统(八)服务端和客户端通信协议编解码

    Netty实战 IM即时通讯系统(八)服务端和客户端通信协议编解码 零. 目录 IM系统简介 Netty 简介 Netty 环境配置 服务端启动流程 客户端启动流程 实战: 客户端和服务端双向通信 数 ...

  5. Netty搭建Http2服务端并支持TLS传输加密

    Netty搭建Http2服务端并支持TLS传输加密 @Slf4j public class SslUtil {public static SslContext sslContext() {SslPro ...

  6. 学习笔记:Java Protocol Buffer的使用和编码原理学习

    一.protocolbuffer简介: protocol buffer 是 google 的一种数据交换的格式,它独立于语言,独立于平台.google 提供了三种语言的实现:java.c++ 和 py ...

  7. Protocol Buffer Basics: C#

    Protocol Buffer 基础知识:c#    原文地址:https://developers.google.com/protocol-buffers/docs/csharptutorial 这 ...

  8. 跨语言RPC框架Hessian、Thrift、Protocol Buffer之间的选择

    为什么80%的码农都做不了架构师?>>>    总结在几者之间选择的考量: 1. 如果你不需要很多语言相互调用, 希望保持清晰的java接口代码(无任何业务不相关的接口继承和方法,属 ...

  9. Google Protocol Buffer 简单介绍

    以下内容主要整理自官方文档. 为什么使用 Protocol Buffers .proto文件 Protocol Buffers 语法 编译.proto文件 Protocol Buffers API 枚 ...

最新文章

  1. Octave Convolution卷积
  2. jmeter怎么在服务器上运行,如何通过jenkins在远程服务器上运行jmeter测试
  3. 【JUC系列】Future异步回调模式
  4. 系统烧写方法(MfgTool烧写工具)
  5. 从核心技术到高可用实践——解密数据库深度挖掘指南
  6. mysql 编译安装与rpm安装的区别_编译安装与RPM安装的区别
  7. python中常见的运行时错误_新手常见Python运行时错误汇总
  8. html标签的引号嵌套,使用YQL多查询&amp; XPath解析HTML,如何转义嵌套引号?
  9. python定时爬取数据_python实现scrapy爬虫每天定时抓取数据的示例代码
  10. linux diff 补丁,Linux中diff、补丁的用法及介绍
  11. JRebel: ERROR Failed to obtain seat. Unable to connect to license server. Check
  12. 关于Win8引导菜单风格切换
  13. 计算三角形网格的tangent space
  14. nxp的wifi驱动调试
  15. 引导最大内存_32位系统内存小的解决方法
  16. android实现仿真键盘(KeyboardView适配)
  17. NETPLIER: Probabilistic Network Protocol Reverse Engineering from Message Traces代码复现记录
  18. textarea文本框的placeholder文字换行
  19. jmeter查看平均响应时间_线上服务平均响应时间太长,怎么排查?
  20. 在Mac OS X苹果lion系统上制作USB启动盘

热门文章

  1. 常用抓包工具(可编程抓包工具)
  2. 大环境下瑟瑟发抖辞职的第二天,拿了两个 offer
  3. 新5 年时间服务器从 0 到 200,一个创业公司的架构野蛮生长史头疼哈
  4. 分享一波Kafka面试题答案
  5. Java线程详解(4)-线程状态的转换
  6. redux-saga 实践总结
  7. 【Scratch】青少年蓝桥杯_每日一题_4.25_说日子
  8. signature=9742dbe4d0ffb25ecc6661da5a37550e,Die Griechische Volkswirtschaft in den siebziger Jahren
  9. redis性能吞吐量瓶颈_面试官:如何用慢查询找到 Redis 的性能瓶颈?
  10. 佛吉尼亚大学计算机世界排名,弗吉尼亚大学计算机世界排名