Netty的Protobuf开发列子

本文档详细介绍了如何使用Protobuf与Netty进行通信,从创建.proto文件开始,通过protoc编译器生成Java代码,将生成的文件放入相应包中,接着分别构建Netty的服务端和客户端,包括核心处理类,并最终展示了运行成功的结果。
摘要由CSDN通过智能技术生成

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.运行结果




运行完美~~~~~~~~~~~~~~~~~~~~~~~~大笑吐舌头偷笑生气

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值