Protobuf多协议
上一篇只有Person的message,如果多了一个message,如Dog,这样就会有问题。
解决方法: 定义多协议
一、定义proto文件
syntax = "proto2"; package com.example.protobuf; option optimize_for = SPEED;
option java_package = "com.example.sixthexample";
option java_outer_classname = "MyDataInfo"; message MyMessage{
enum DataType{
PersonType = 1;
DogType = 2;
CatType = 3;
} required DataType data_type = 1;
oneof dataBody{
Person person = 2;
Dog dog = 3;
Cat cat = 4;
} } message Person{
optional string name = 1;
optional int32 age = 2;
optional string address = 3; } message Dog{
optional string name = 1;
optional int32 age = 2;
} message Cat{
optional string name = 1;
optional string city = 2;
}
然后用命令生成
D:\workspace\study\basic\netty_demo>protoc --java_out=src/main/java src/protobuf/Person2.proto
二、客户端代码
1、TestClient 类,和上一篇一样
public class TestClient {
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 TestClientInitializer());
ChannelFuture channelFuture = bootstrap.connect("localhost",8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
eventLoopGroup.shutdownGracefully();
}
}
}
2、TestClientHandle 类
public class TestClientHandle extends SimpleChannelInboundHandler<MyDataInfo.Person> {
// 对于客户端来说,输入来自控制台
@Override
protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.Person msg) throws Exception {
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//客户端启动后,将消息发送给服务端
int randomInt = new Random().nextInt(3);
MyDataInfo.MyMessage myMessage = null;
if(0 == randomInt){
MyDataInfo.Person person = MyDataInfo.Person.newBuilder()
.setName("张三").setAge(30).setAddress("上海").build();
myMessage = MyDataInfo.MyMessage.newBuilder()
.setDataType(MyDataInfo.MyMessage.DataType.PersonType)
.setPerson(person).build();
}else if(1 == randomInt){
MyDataInfo.Dog dog = MyDataInfo.Dog.newBuilder()
.setName("一只狗").setAge(10).build();
myMessage = MyDataInfo.MyMessage.newBuilder()
.setDataType(MyDataInfo.MyMessage.DataType.DogType)
.setDog(dog).build();
}else{
MyDataInfo.Cat dog = MyDataInfo.Cat.newBuilder()
.setName("一只猫").setCity("杭州").build();
myMessage = MyDataInfo.MyMessage.newBuilder()
.setDataType(MyDataInfo.MyMessage.DataType.CatType)
.setCat(dog).build();
}
ctx.channel().writeAndFlush(myMessage);
}
}
3、TestClientInitializer 改变的地方,如下图红色部分

三、服务端
1、TestServer 和上一篇一样
public class TestServer {
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 TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
2、TestServerHandle 类
public class TestServerHandle extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception {
System.out.println("---- 服务端接收到消息 ----");
MyDataInfo.MyMessage.DataType dataType = msg.getDataType();
if(dataType == MyDataInfo.MyMessage.DataType.PersonType){
MyDataInfo.Person person = msg.getPerson();
System.out.println(person.getName());
System.out.println(person.getAge());
System.out.println(person.getAddress());
}else if(dataType == MyDataInfo.MyMessage.DataType.DogType){
MyDataInfo.Dog dog = msg.getDog();
System.out.println(dog.getName());
System.out.println(dog.getAge());
}else {
MyDataInfo.Cat cat = msg.getCat();
System.out.println(cat.getName());
System.out.println(cat.getCity());
}
}
}
3、TestServerInitializer 改变的地方,如下图红色部分

四、测试
1、启动服务端
2、启动多个客户端
3、服务端输出

Protobuf多协议的更多相关文章
- netty中使用protobuf实现多协议的消息
在我们使用 netty 的过程中,有时候为了高效的传输数据,经常使用 protobuf 进行数据的传输,netty默认情况下为我们实现的 protobuf 的编解码,但是默认的只能实现单个对象的编解码 ...
- Netty对Protocol Buffer多协议的支持(八)
Netty对Protocol Buffer多协议的支持(八) 一.背景 在上篇博文中笔者已经用代码演示了如何在netty中使用Protocol Buffer,然而细心的用户可能会发现一个明显的不足之处 ...
- python通过protobuf实现rpc
由于项目组现在用的rpc是基于google protobuf rpc协议实现的,所以花了点时间了解下protobuf rpc.rpc对于做分布式系统的人来说肯定不陌生,对于rpc不了解的童鞋可以自行g ...
- Protobuf使用规范分享
一.Protobuf 的优点 Protobuf 有如 XML,不过它更小.更快.也更简单.它以高效的二进制方式存储,比 XML 小 3 到 10 倍,快 20 到 100 倍.你可以定义自己的数据结构 ...
- java netty socket库和自定义C#socket库利用protobuf进行通信完整实例
之前的文章讲述了socket通信的一些基本知识,已经本人自定义的C#版本的socket.和java netty 库的二次封装,但是没有真正的发表测试用例. 本文只是为了讲解利用protobuf 进行C ...
- 在Wcf中应用ProtoBuf替代默认的序列化器
Google的ProtoBuf序列化器性能的牛逼已经有目共睹了,可以把它应用到Socket通讯,队列,Wcf中,身为dotnet程序员一边期待着不久后Grpc对dotnet core的支持更期待着Wc ...
- protobuf的编译安装
github地址:https://github.com/google/protobuf支持多种语言,有多个语言的版本,本文采用的是在centos7下编译源码进行安装. github上有详细的安装说明: ...
- 编译protobuf的jar文件
1.准备工作 需要到github上下载相应的文件,地址https://github.com/google/protobuf/releases protobuf有很多不同语言的版本,因为我们需要的是ja ...
- protobuf学习(2)-相关学习资料
protobuf官方git地址 protobuf官方英文文档 (你懂的需要FQ) protobuf中文翻译文档 protobuf概述 (官方翻译 推荐阅读) protobuf入门 ...
随机推荐
- 笔谈AudioToolbox(一)
“五一”长假过的真快,三天就这么过去了.新的一周开始了,这周搞搞iOS平台上音频的解码与播放.动手咯,切入AudioToolbox.framework的学习,这个库太强大了,要想彻底弄懂不简单,从某种 ...
- Python入门篇-类型注解
Python入门篇-类型注解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.函数定义的弊端 1>.动态语言很灵活,但是这种特性也是弊端 Python是动态语言,变量随时可 ...
- go语言笔记1
Go语言学习整理 本文基于菜鸟教程,对于自己不明白的点加了点个人注解,对于已明确的点做了删除,可能结构不太清晰,看官们可移步Go语言教程 1 Go语言结构当标识符(包括常量.变量.类型.函数名. ...
- 玩转Fiddler抓包工具
一.Fiddler简述 Fiddler是最强大最好用的Web调试工具之一, 它能记录所有客户端和服务器的http和https请求.允许你监视.设置断点.甚至修改输入输出数据.Fiddler包含了一个强 ...
- MySQL与安全
说到MySQL数据库的安全性,可能有大量的相关话题,下面将对几个关键问题进行概括性描述. (1)安全的一般性因素.包括使用强密码,禁止给用户分配不必要的权限,防止SQL注入攻击. (2)安装步骤的安全 ...
- 与你一起学习MS Project——理论篇:项目管理与Project
Hi,你好!我是大黄蜂,非常高兴借此机会与你一起学习微软Project的相关知识和技能.这一次的分享主要是结合本人在实际使用Project 2013过程中的一些方法技巧,其中有一些材料则来源于互联网, ...
- 用python做数据分析pandas库介绍之DataFrame基本操作
怎样删除list中空字符? 最简单的方法:new_list = [ x for x in li if x != '' ] 这一部分主要学习pandas中基于前面两种数据结构的基本操作. 设有DataF ...
- pycharm激活2018(终极解决办法)
1.将“0.0.0.0 account.jetbrains.com”中的内容添加到hosts文件中,hosts路径为:C:\Windows\System32\drivers\etc 2.打开http: ...
- LOJ P10004 智力大冲浪 题解
每日一题 day37 打卡 Analysis 经典的带限期和罚款的单位时间任务调度问题 将 val 从大到小排序,优先处理罚款多的,将任务尽量安排在期限之前,并且靠后,如果找不到,则放在最后面 #in ...
- python 字符串方法整理
Python字符串方法 1.大小写转换 1.1 lower.upper lower():小写 upper():大写 1.2 title.capitalize S.title():字符串中所有单词首字母 ...