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. bitcms内容管理系统 3.1版源码发布

    开源bitcms内容管理系统采用ASP.NET MVC5+MySql的组合开发,更适应中小型系统低成本运行. bitcms的主要功能 1.重写了APS.NET MVC的路由机制.bitcms使用路由参 ...

  2. php之str_replace具体解释

    str_replace (PHP 4, PHP 5) str_replace - Replace all occurrences of the search string with the repla ...

  3. IntelliJ IDEA(五) :Settings(中)

    上篇介绍了Settings中的Appearance & Behavior和Keymap,这篇继续,将介绍Editor,Plugins,Version Control. 一.Editor(编辑) ...

  4. Uva 10550 Combination Lock

    Sample Input0 30 0 305 35 5 350 20 0 207 27 7 270 10 0 109 19 9 190 0 0 0Sample Output13501350162016 ...

  5. Java面向对象的特征

    面向对象的特征 封装.继承.多态.(有人问第四个特征,再加抽象) 封装 体现形式(2种) 函数---提高代码的复用性 属性的私有化---将属性设置为私有的,通过提供对外的访问方法来间接操作对应属性,可 ...

  6. Bandit Wargame Level24 Writeup(brute-forcing with shell)

    Bandit Level 24 → Level 25 Level Goal A daemon is listening on port 30002 and will give you the pass ...

  7. 分布式:2PC,3PC,Paxos,Raft,ISR [转]

    本文主要讲述2PC及3PC,以及Paxos以及Raft协议. 两类一致性(操作原子性与副本一致性) 2PC协议用于保证属于多个数据分片上的操作的原子性.这些数据分片可能分布在不同的服务器上,2PC协议 ...

  8. 阿里云服务器(windows server2008)下安装SVN----杜恩德

    我想说的是如何在阿里云上建立SVN版本,供外网访问,上传代码 在阿里云服务器上安装svn与在本地安装是一样的, ----参考 http://blog.csdn.net/m0_37027631/arti ...

  9. 《极客与团队》【PDF】下载

    <极客与团队>[PDF]下载链接: https://u253469.ctfile.com/fs/253469-231196337 内容简介 软件开发是一项团队运动,人的因素对结果的影响完全 ...

  10. 数据加密,android客户端和服务器端可共用

    安卓中,不管是内网还是外网,数据的传输首要考虑就是安全问题,尤其是用户信息,以及各种密码等敏感信息. 所以说,对数据的加密是很有必要的,尤其是当下物联网蓬勃发展的今天,数据安全尤为重要. 数据加密的方 ...