Netty的Protobuf开发列子
2016-05-01 15:16
447 查看
1.首先创建.proto文件
SubscribeReq.proto文件package com.netty.code.protobuf; option java_package = "com.phei.netty.protobuf"; option java_outer_classname = "SubscribeReqProto"; message SubscribeReq{ required int32 subReqID= 1; required string userName = 2; required string productName= 3; repeated string address = 4; }SubscribeResp.proto文件
package com.netty.code.protobuf; option java_package = "com.phei.netty.protobuf"; option java_outer_classname = "SubscribeRespProto"; message SubscribeResp{ required int32 subReqID = 1; required int32 respCode = 2; required string desc = 3; }
2.通过protoc.exe,生成java文件
3. 将生成的java文件拷贝到相应的包下
4.Netty服务端类
package com.phei.netty.protobuf; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; /** * 服务端 * @author renhj * */ public class SubReqServer { public void bind(int port) throws Exception{ //第一个用户服务器接收客户端的连接 EventLoopGroup bossGroup = new NioEventLoopGroup(); //第二个用户SocketChannel的网络读写 EventLoopGroup workerGroup = new NioEventLoopGroup(); try{ //创建ServerBootstrap对象,启动 NIO服务端的辅助启动类 ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup). //设置为NIO channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChildChannelHandler()); //绑定端口,同步等待成功 ChannelFuture f = b.bind(port).sync(); //等待服务器监听端口关闭 f.channel().closeFuture().sync(); }finally{ //释放线程池资源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{ @Override protected void initChannel(SocketChannel ch) throws Exception { //处理半包问题 ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); //添加ProtobufDecoder解码器 ch.pipeline().addLast(new ProtobufDecoder(SubscribeReqProto.SubscribeReq.getDefaultInstance())); ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); ch.pipeline().addLast(new ProtobufEncoder()); ch.pipeline().addLast(new SubReqServerHandler()); } } public static void main(String[] args) throws Exception { int port = 8080; if(args != null && args.length>0){ try{ port = Integer.valueOf(args[0]); }catch(Exception e){ //采用默认值 } } new SubReqServer().bind(port); } }
5.Netty服务端核心处理类
package com.phei.netty.protobuf; import java.util.Date; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; /** * 服务端核心处理类 * @author renhj * */ public class SubReqServerHandler extends ChannelHandlerAdapter { private int counter; @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq)msg; if("Lilinfeng".equalsIgnoreCase(req.getUserName())){ System.out.println("Server accept client subsrcibe req :["+req.toString()+"]"); ctx.writeAndFlush(resp(req.getSubReqID())); } } private SubscribeRespProto.SubscribeResp resp(int subReqID){ SubscribeRespProto.SubscribeResp.Builder builder = SubscribeRespProto.SubscribeResp.newBuilder(); builder.setSubReqID(subReqID); builder.setRespCode(0); builder.setDesc("Netty book succeed, 3 days later , sent to the designated address "); return builder.build(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }
6.Netty客户端类
package com.phei.netty.protobuf; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; 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.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.handler.codec.string.StringDecoder; /** * 客服端 * @author renhj * */ public class SubReqClient { public void connect(int port , String host) throws Exception{ //配置客户端NIO线程组 EventLoopGroup group = new NioEventLoopGroup(); try{ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>(){ @Override public void initChannel(SocketChannel ch) throws Exception{ //处理半包问题 ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); //添加ProtobufDecoder解码器 ch.pipeline().addLast(new ProtobufDecoder(SubscribeRespProto.SubscribeResp.getDefaultInstance())); ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); ch.pipeline().addLast(new ProtobufEncoder()); ch.pipeline().addLast(new SubReqClientHandler()); } }); //发起异步连接操作 ChannelFuture f = b.connect(host, port).sync(); //等待客户端链路关闭 f.channel().closeFuture().sync(); }finally{ //释放NIO线程 group.shutdownGracefully(); } } public static void main(String[] args) throws Exception{ int port = 8080; if(args !=null && args.length>0){ try{ port = Integer.valueOf(args[0]); }catch(Exception e){ } } new SubReqClient().connect(port, "127.0.0.1"); } }
7.Netty客户端核心处理类
package com.phei.netty.protobuf; import java.util.ArrayList; import java.util.List; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; /** * 客户端核心处理类 * @author renhj * */ public class SubReqClientHandler extends ChannelHandlerAdapter { public SubReqClientHandler(){ } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { for(int i=0;i<10;i++){ ctx.write(subReq(i)); } ctx.flush(); } private SubscribeReqProto.SubscribeReq subReq(int i){ SubscribeReqProto.SubscribeReq.Builder builder = SubscribeReqProto.SubscribeReq.newBuilder(); builder.setSubReqID(i); builder.setUserName("Lilinfeng"); builder.setProductName("Netty Book For Protobuf"); List<String> address = new ArrayList<String>(); address.add("NanJing YuHuaTai"); address.add("BeiJing LiuLiChang"); builder.addAllAddress(address); return builder.build(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("Receive server response : ["+msg+"]"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { //释放资源 ctx.close(); } }
8.运行结果
运行完美~~~~~~~~~~~~~~~~~~~~~~~~
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/tongue.gif)
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/mad.gif)
相关文章推荐
- leetcode 061 Rotate List
- ubuntu安装VMware Tools报错enter the path to the kernel header files
- 彻底消除wine中文乱码,QQ,kugoo等等....
- C语言中的restrict,const,volatile
- 用 Apache JMeter 测试 WebSphere 性能
- leetcode——120——Triangle
- 算法(五)
- 关于 JavaScript 如何去掉字符串中标签的方法
- hdu 2647 Reward
- 2014年武汉的IT行情好像不太好(续):20个月过后,再看当时面试过的几个公司--武汉财富基石-崩盘,辣妈萌宝-创业失败,朋友公司转交他人管理
- 2014年武汉的IT行情好像不太好(续):20个月过后,再看当时面试过的几个公司--武汉财富基石-崩盘,辣妈萌宝-创业失败,朋友公司转交他人管理
- 修改VLC读缓冲机制
- 2014年武汉的IT行情好像不太好(续):20个月过后,再看当时面试过的几个公司--武汉财富基石-崩盘,辣妈萌宝-创业失败,朋友公司转交他人管理
- hdu 1754
- ZOJ - 3869 Ace of Aces (水)
- vs中如何统计整个项目的代码行数
- vs中如何统计整个项目的代码行数
- jstl中<c:forEach>的用法
- 全国SHP地图数据赠送
- linux Xtrabackup安装及使用方法