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. 制作多级菜单hide()与show() toggle()

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. 自学Python全栈开发的第二次笔记(Python需要注意的地方)

    好几天没写blog了,今天整理整理.写blog一定要坚持下去.     Python解释器 #!/usr/bin/env python #-*-coding:utf-8-*-   #  无效的内容,只 ...

  3. 剑指Offer_12_矩阵中的路径(参考问题:马踏棋盘)

    题目描述  请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径.路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子.如果一条路径经过了矩阵 ...

  4. LintCode-买卖股票的最佳时机

    如果有一个数组,它的第i个元素是一支给定的股票在第i天的价格.如果你最多仅仅同意完毕一次交易(比如,一次买卖股票),设计一个算法来找出最大利润. 您在真实的面试中是否遇到过这个题? Yes 例子 给出 ...

  5. Android后台执行的定时器实现

    Android后台运行定时器,方便我们运行定位跟踪等任务需求. 以下简要说明实现Android后台定时器的要点, 文章末尾能够下载到project代码,可直接编译运行. AndroidManifest ...

  6. 【JAVA零基础入门系列】Day1 开发环境搭建

    [JAVA零基础入门系列](已完结)导航目录 Day1 开发环境搭建 Day2 Java集成开发环境IDEA Day3 Java基本数据类型 Day4 变量与常量 Day5 Java中的运算符 Day ...

  7. Mybatis中如何将POJO作为参数传入sql

    今天在工作时,需要将获取的用户的注册信息插入数据库,开始的做法是将所有的model的属性作为DAO接口的参数,后来想想不对劲,要是有100个属性,那我这个接口岂不是要有100个参数传进来? 于是我就考 ...

  8. MyBatis_延迟加载01

    一.延迟加载 MyBatis中的延迟加载,也称为懒加载,是指在进行关联查询时, 按照设置延迟规则推迟对关联对象的select查询.延迟加载可以有效的减少数据库压力. MyBatis的延迟加载只是对关联 ...

  9. Python笔记·第九章—— 函数 (一)

    一.函数的作用 函数可以让我们代码结构更清晰,而且避免了代码的重复,冗余,使一段代码或者功能可以反复的被调用,大大提高了开发效率 二.函数的定义 def 函数名(参数1,参数2,*args,默认参数, ...

  10. Ubuntu安装微信开发者工具

    参考教程:https://ruby-china.org/topics/30339 1.下载nw sdk $ wget -c http://dl.nwjs.io/v0.15.3/nwjs-sdk-v0. ...