Netty的Protobuf开发列子
来源:互联网 发布:ruby for windows 编辑:程序博客网 时间:2024/05/16 18:01
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>{@Overrideprotected 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; @Overridepublic 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();}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overridepublic 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>(){@Overridepublic 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(){}@Overridepublic 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();}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println("Receive server response : ["+msg+"]");}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {//释放资源ctx.close();} }
8.运行结果
运行完美~~~~~~~~~~~~~~~~~~~~~~~~
1 0
- Netty的Protobuf开发列子
- protobuf+netty的demo
- Netty+ProtoBuf的实例教程
- Netty的protobuf的图书订购服务端开发
- Netty 之 Netty使用Google的ProtoBuf
- netty与protobuf结合开发小demo
- protobuf在netty里面的应用举例
- protobuf在netty里面的应用举例
- protobuf在netty里面的应用举例
- protobuf在netty里面的应用举例 .
- Netty与Google的protobuf使用
- netty:protobuf的编码器ProtobufVarint32LengthFieldPrepender()、解码器ProtobufVarint32FrameDecoder()
- protobuf在netty里面的应用举例
- Netty protobuf的编解码使用
- Netty集成Google的ProtoBuf序列化
- Netty Protobuf C# 通信
- 【Netty基础】protobuf详解
- [netty]-消息编解码之google的Protobuf编解码
- POJ 3321Apple Tree(dfs序 树状数组)
- secureCRT光标不见啦
- 利用referer请求头防止“盗链”
- PHP基础之进制的转换
- 一个xib文件中最有一个view
- Netty的Protobuf开发列子
- 96. Unique Binary Search Trees
- zlib交叉编译
- Encapsulation and Requiring Files
- 指针做形参新发现
- configure: error: no acceptable C compiler found in $PATH 问题解决
- 安装linuxdash后nginx配置与原有wordpress的error解决
- android中ListView的基本组件及用法
- 用Jmeter进行接口压力测试的步骤