Netty对Protocol Buffer多协议的支持(八)
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 = ;
dogType = ;
} required DataType data_type = ; oneof type_data{
Person person = ;
Dog dog = ;
}
} message Person{
required int32 id = ;
optional string name = ; enum Gender {
male = ;
female = ;
} optional Gender gender = ;
} message Dog {
required float height = ;
optional string color = ;
optional int64 age = ;
}
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>{
@Override
protected 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>{
@Override
protected 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>{
@Override
protected 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>{
@Override
protected 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());
}
@Override
public 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);
}
}
三.运行
运行服务端启动代码,再运行客户端启动代码。
Netty对Protocol Buffer多协议的支持(八)的更多相关文章
- Netty对Protocol Buffer的支持(七)
Netty对Protocol Buffer的支持(七) 一.简介 在上一篇博文中笔者已经介绍了google的Protocol Buffer的使用,那么本文笔者就开始介绍netty对Protocol B ...
- gRPC in ASP.NET Core 3.x -- Protocol Buffer(2)Go语言的例子(上)
上一篇文章(大约半年前写的):https://www.cnblogs.com/cgzl/p/11246324.html 建立Go项目 在GOPATH的src下面建立一个文件夹 protobuf-go, ...
- Netty使用Google Protocol Buffer完成服务器高性能数据传输
一.什么是Google Protocol Buffer(protobuf官方网站) 下面是官网给的解释: Protocol buffers are a language-neutral, platfo ...
- Protocol Buffer技术
转载自http://www.cnblogs.com/stephen-liu74/archive/2013/01/02/2841485.html 该系列Blog的内容主体主要源自于Protocol Bu ...
- 理解netty对protocol buffers的编码解码
一,netty+protocol buffers简要说明 Netty是业界最流行的NIO框架之一优点:1)API使用简单,开发门槛低:2)功能强大,预置了多种编解码功能,支持多种主流协议:3)定制能力 ...
- Protocol Buffer技术详解(语言规范)
Protocol Buffer技术详解(语言规范) 该系列Blog的内容主体主要源自于Protocol Buffer的官方文档,而代码示例则抽取于当前正在开发的一个公司内部项目的Demo.这样做的目的 ...
- Protocol Buffer基本介绍
转自:http://www.cnblogs.com/stephen-liu74/archive/2013/01/02/2841485.html 该系列Blog的内容主体主要源自于Protocol Bu ...
- netty4与protocol buffer结合简易教程
各项目之间通常使用二进制进行通讯,占用带宽小.处理速度快~ 感谢netty作者Trustin Lee.让netty天生支持protocol buffer. 本实例使用netty4+protobuf-2 ...
- Protocol Buffer搭建及示例
本文来源:http://www.tanhao.me/code/150911.html/ Protocol Buffer(简称Protobuf或PB)是由Google推出的一种数据交换格式,与传统的XM ...
随机推荐
- 对datatable进行简单的操作
筛选出datatable中c_level=1的数据 dataRow[] rows = dt.Select("c_level=0"); 克隆表dt的结构到表dt,并将dt的数据复制到 ...
- 參与 Spring 4 中文文档翻译
參与 Spring 4 中文文档翻译 我们从2014年12月開始翻译Spring 4的框架文档.尽管至今已有一年,可是进度非常慢. 当中一部分原因是由于Spring 文档有1000多页,并且翻译的时候 ...
- 我的GIS观
申明: 文章所述观点与不论什么组织或个人无关,仅代表我个人观点,如有不正确,还望批评指正. 概述: 从毕业到如今,在GIS这条路上也算是摸爬滚打4.5年了.说长也不长,说短也不短.在这4.5年的时间里 ...
- Node.js开发Web后台服务
一.简介 Node.js 是一个基于Google Chrome V8 引擎的 JavaScript 运行环境.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效.Node.j ...
- 一起读源码之zookeeper(1) -- 启动分析
从本文开始,不定期分析一个开源项目源代码,起篇从大名鼎鼎的zookeeper开始. 为什么是zk,因为用到zk的场景实在太多了,大部分耳熟能详的分布式系统都有zookeeper的影子,比如hbase, ...
- Spring官方文档翻译
随笔:有人曾这样评价spring,说它是Java语言的一个巅峰之作,称呼它为Java之美,今天,小编就领大家一起来领略一下spring之美! Spring官方文档:http://docs.spring ...
- 翻译:Identifier Qualifiers标识限定符
*/ .hljs { display: block; overflow-x: auto; padding: 0.5em; color: #333; background: #f8f8f8; } .hl ...
- 前端开发JavaScript清除浏览器缓存的方法
查看和删除浏览器缓存的方法=====>打开 最近在开发项目中发现有时候总要频繁地清除浏览器缓存,不然总是显示的过时的信息 浏览器缓存有利有弊,有些数据需要缓存下来使得页面打开更快提高网站性能,但 ...
- IO流(File类,IO流的分类,字节流和字符流,转换流,缓冲流,对象序列化)
1.File类 File类可以在程序中 操作文件和目录.File类是通过建立File类对象,在调用File类的对象来进行相关操作的. 示例: public class Demo01 { public ...
- CentOS 7 学习(四)Git配置(一)
CentOS 7 学习(四)Git配置(一) 1.对于版本管理系统,目前常用的是Subverion和Git,Subversion是集中式版本管理系统中最好的,所有人的代码都要提交到服务器上,如果要知道 ...