netty4与protocol buffer结合简易教程
各项目之间通常使用二进制进行通讯,占用带宽小、处理速度快~
感谢netty作者Trustin Lee。让netty天生支持protocol buffer。
本实例使用netty4+protobuf-2.5.0。在win7下运行。而且如果已经安装jdk和maven。
1、下载并解压protoc-2.5.0-win32.zip和protobuf-2.5.0.zip
2、到protobuf-2.5.0.zip安装文件夹protobuf-2.5.0\java下,运行maven命令:mvn package jar:jar,将生成target\protobuf-java-2.5.0.jar
3、定义proto文件test.proto:
package domain;
option java_package = "com.server.domain";
message TestPro {
required string test = 1;
}
4、将第2部的jar包复制到java文件存放文件夹下,然后执行以下命令,生成java文件:
protoc-2.5.0-win32.zip安装文件夹\protoc.exe --java_out=java文件存放文件夹 proto定义文件文件夹\test.proto
5、将生成的protobuf-java-2.5.0.jar和netty4的jar包放到项目的classpath中,并将第4部生成的java文件放到项目的对应路径下。
6、编写Server端代码
1)、编写handler类:
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ServerHandler extends SimpleChannelInboundHandler<Test.TestPro> {
@Override
public void channelRead0(ChannelHandlerContext ctx, Test.TestPro msg) throws Exception {
System.out.println("server:" + "channelRead:" + msg.getTest());
Test.TestPro.Builder builder = Test.TestPro.newBuilder();
builder.setTest("Received your message !");
ctx.writeAndFlush(builder.build());
}
}
2)、注冊服务,绑定port:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
public class Server {
public static void main(String[] args) {
EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup();
EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast("encoder", new ProtobufEncoder());
ch.pipeline().addLast("decoder", new ProtobufDecoder(Test.TestPro.getDefaultInstance()));
ch.pipeline().addLast("handler", new ServerHandler());
};
});
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
bossEventLoopGroup.shutdownGracefully();
workerEventLoopGroup.shutdownGracefully();
}
}
}
7、编写Client端代码
1)、定义Client端的handler类:
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class ClientHandler extends SimpleChannelInboundHandler<Test.TestPro> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Test.TestPro msg) throws Exception {
System.out.println("client:" + "channelRead:" + msg.getTest());
}
}
2)、建立Client端到Server端的连接
import java.io.BufferedReader;
import java.io.InputStreamReader;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class Client {
public static void main(String[] args) {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast("encoder", new ProtobufEncoder());
ch.pipeline().addLast("decoder", new ProtobufDecoder(Test.TestPro.getDefaultInstance()));
ch.pipeline().addLast("handler", new ClientHandler());
};
});
Channel ch = bootstrap.connect("127.0.0.1", 8888).sync().channel();
// 控制台输入
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
String line = in.readLine();
if (line == null || "".equals(line)) {
continue;
}
Test.TestPro.Builder builder = Test.TestPro.newBuilder();
builder.setTest(line);
ch.writeAndFlush(builder.build());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
eventLoopGroup.shutdownGracefully();
}
}
}
新手教程,欢迎拍砖。
推荐其它參考教程:protocol与netty结合的资料http://blog.csdn.net/goldenfish1919/article/details/6719276
netty4与protocol buffer结合简易教程的更多相关文章
- Protocol Buffer学习教程之类库应用(四)
Protocol Buffer学习教程之类库应用(四) 此教程是通过一个简单的示例,给C++开发者介绍一下如何使用protocol buffers编程,主要包括以下几部分: 定义一个.proto文件 ...
- Protocol Buffer学习教程之编译器与类文件(三)
Protocol Buffer学习教程之编译器与类文件(三) 1. 概述 在前面两篇中,介绍了Protobuf的基本概念.应用场景.与protobuf的语法等.在此篇中将介绍如何自己编译protobu ...
- 从零开始山寨Caffe·伍:Protocol Buffer简易指南
你为Class外访问private对象而苦恼嘛?你为设计序列化格式而头疼嘛? ——欢迎体验Google Protocol Buffer 面向对象之封装性 历史遗留问题 面向对象中最矛盾的一个特性,就是 ...
- Protocol Buffer学习教程之语法手册(二)
1.说明 此向导介绍如何使用protocol buffer language创建一个自己的protocolbuffer文件,包括语法与如何通过“.proto”文件生成数据访问的类,此处只介绍proto ...
- Protocol Buffer学习教程之开篇概述(一)
1. Protocol Buffer是什么 Protocol Buffer是google旗下的产品,用于序列化与反序列化数据结构,但是比xml更小.更快.更简单,而且能跨语言.跨平台.你可以把你的数据 ...
- Google Protocol Buffer 的使用和原理[转]
本文转自: http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/ Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构 ...
- Emacs简易教程
Emacs简易教程阅读: 命令: $emacs 进入之后,输入: C-h t 这里,C-h表示按住[Ctrl]键的同时按h ####### 20090620 *退出: 输入“C-x C-c” *撤销: ...
- protocol buffer使用简介
之前在工作中用到了protocol buffer(此处简称PB)(主要对数据进行序列化与反序列化,方便网络传输中的编解码),之后发现这是一个好东西,在此稍微记录下该工具如何使用,方便以后查阅 官网地址 ...
- [翻译]Protocol Buffer 基础: C++
目录 Protocol Buffer Basics: C++ 为什么使用 Protocol Buffers 在哪可以找到示例代码 定义你的协议格式 编译你的 Protocol Buffers Prot ...
随机推荐
- (转) 淘淘商城系列——CMS内容管理系统工程搭建
http://blog.csdn.net/yerenyuan_pku/article/details/72825801 淘淘商城系列——CMS内容管理系统工程搭建 上文我们一起搭建了表现层中的商城门户 ...
- Swift 命名空间形式扩展的实现
Swift 的 extension 机制很强大,不仅可以针对自定义的类型,还能作用于系统库的类型,甚至基础类型比如 Int.当在对系统库做 extension 的时候,就会涉及到一个命名冲突的问题.O ...
- Locations for Public Frameworks
Locations for Public Frameworks Third-party frameworks can go in a number of different file-system l ...
- php腾讯云短信验证码
腾讯云短信控制台:https://console.cloud.tencent.com/sms 腾讯云短信 PHP SDK:https://github.com/qcloudsms/qcloudsms_ ...
- How To: IDENTIFY THE ASM DEVICE FROM ASMLIB
使用oracleasm querydisk可以查询到device的major和minor,从而对应. for i in `oracleasm listdisks` do oracleasm query ...
- cacheStorage缓存及离线开发
案例地址:https://zhangxinxu.github.io/https-demo/cache/start.html 我们直接看一个例子吧,如下HTML和JS代码: <h3>一些提示 ...
- CF508E Arthur and Brackets
题目大意:给出n对括号,并给出每对括号距离的范围.问能否找到这样一个序列. 题解:好多人都用贪心.这么好的题为什么不搜一发呢? 注意:千万不要在dfs里面更新答案. 代码: #include<c ...
- spring的IOC的简单理解
之前看了一下源码,看的挺吃力,只能是慢慢看了. 简单说一下springIOC的我的理解,IOC也叫控制反转,可以有效的减低各个组件之间的耦合度 想象一下,如果不用IOC,那么系统里面会有大量的new ...
- 编译时报错,找不到指定路径下的command,而路径是正确的。
使用的Fedora 18 64位的系统kernel,内核为3.6.10.按照要求使用yum install *** 安装各项工具. path路径使用提供的toolchain,各种路径也安装正确,却发现 ...
- python爬虫(三)
Requests模块 这个库的标准文档有个极其幽默的地方就是它的中文翻译,我就截取个开头部分,如下图: 是不是很搞笑,在正文中还有许多,管中窥豹,可见一斑.通过我的使用,感觉Requests库的确是给 ...