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多协议的支持(八)的更多相关文章

  1. Netty对Protocol Buffer的支持(七)

    Netty对Protocol Buffer的支持(七) 一.简介 在上一篇博文中笔者已经介绍了google的Protocol Buffer的使用,那么本文笔者就开始介绍netty对Protocol B ...

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

    上一篇文章(大约半年前写的):https://www.cnblogs.com/cgzl/p/11246324.html 建立Go项目 在GOPATH的src下面建立一个文件夹 protobuf-go, ...

  3. Netty使用Google Protocol Buffer完成服务器高性能数据传输

    一.什么是Google Protocol Buffer(protobuf官方网站) 下面是官网给的解释: Protocol buffers are a language-neutral, platfo ...

  4. Protocol Buffer技术

    转载自http://www.cnblogs.com/stephen-liu74/archive/2013/01/02/2841485.html 该系列Blog的内容主体主要源自于Protocol Bu ...

  5. 理解netty对protocol buffers的编码解码

    一,netty+protocol buffers简要说明 Netty是业界最流行的NIO框架之一优点:1)API使用简单,开发门槛低:2)功能强大,预置了多种编解码功能,支持多种主流协议:3)定制能力 ...

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

    Protocol Buffer技术详解(语言规范) 该系列Blog的内容主体主要源自于Protocol Buffer的官方文档,而代码示例则抽取于当前正在开发的一个公司内部项目的Demo.这样做的目的 ...

  7. Protocol Buffer基本介绍

    转自:http://www.cnblogs.com/stephen-liu74/archive/2013/01/02/2841485.html 该系列Blog的内容主体主要源自于Protocol Bu ...

  8. netty4与protocol buffer结合简易教程

    各项目之间通常使用二进制进行通讯,占用带宽小.处理速度快~ 感谢netty作者Trustin Lee.让netty天生支持protocol buffer. 本实例使用netty4+protobuf-2 ...

  9. Protocol Buffer搭建及示例

    本文来源:http://www.tanhao.me/code/150911.html/ Protocol Buffer(简称Protobuf或PB)是由Google推出的一种数据交换格式,与传统的XM ...

随机推荐

  1. sqoop实现关系型数据库与hadoop之间的数据传递-import篇

    由于业务数据量日益增长,计算量非常庞大,传统的数仓已经无法满足计算需求了,所以现在基本上都是将数据放到hadoop平台去实现逻辑计算,那么就涉及到如何将oracle数仓的数据迁移到hadoop平台的问 ...

  2. 基于 HTML5 Canvas 的 3D 压力器反序列化

    在实际应用中,我觉得能够通过操作 JSON 文件来操作 3D 上的场景变化是非常方便的一件事,尤其是在做编辑器进行拖拽图元并且在图元上产生的一系列变化的时候,都能将数据很直观地反应给我们,这边我们简单 ...

  3. myBatis数据库常用标签

    <sql id=""></sql>:封装sql语句,被其他sql调用 <include refid=""></incl ...

  4. java的热部署和热加载

    ps:热部署和热加载其实是两个类似但不同的概念,之前理解不深,so,这篇文章重构了下. 一.热部署与热加载 在应用运行的时升级软件,无需重新启动的方式有两种,热部署和热加载. 对于Java应用程序来说 ...

  5. 《Linux Device Drivers》第十八章 TTY驱动程序——note

    简单介绍 tty设备的名称是从过去的电传打字机缩写而来,最初是指连接到Unix系统上的物理或虚拟终端 Linux tty驱动程序的核心紧挨在标准字符设备驱动层之下,并提供了一系列的功能,作为接口被终端 ...

  6. 谈谈单元測试之(二):測试工具 JUnit 3

    前言 上一篇文章<为什么要进行烦人的单元測试?>讨论了一下现阶段软件开发中,程序猿们測试情况的现状.这篇文章中,我打算介绍一下单元測试的工具(插件).而且推荐大家以后在开发中,真正的用上单 ...

  7. HDOJ 4251 The Famous ICPC Team Again

    划分树水题..... The Famous ICPC Team Again Time Limit: 30000/15000 MS (Java/Others)    Memory Limit: 3276 ...

  8. 查询linux版本命令

    [环境] Ubuntu [本文命令记录] uname -a lsb_release cat /etc/issue cat /proc/version [截图效果] (1)uname -a (2)lsb ...

  9. Springboot-添加对jsp支持

    1,在项目的配置文件加入以下依赖 <dependency> <groupId>javax.servlet</groupId> <artifactId>j ...

  10. org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

    异常信息 org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable represen ...