netty学习七:集成protobuf完成单个对象序列化以及在网络上传输

概述


本文介绍使用netty集成google的protobuf框架,完成proto JAVA对象的序列化和反序列化。


编写proto文件


protobuf使用.proto文件来描述对象结构体的信息。
Person.proto文件的位置

src/main/java/protobuf/seconddemo/Person.proto

syntax = "proto2";
package protobuf;
option optimize_for=SPEED;
option java_package="protobuf.seconddemo";
option java_outer_classname="ModelInfo";

message Person {
  required string name = 1;
  optional int32 age = 2;
  optional string address = 3;
}

使用proto编译器生成java对象


protoc –java_out=src/main/java src/main/java/protobuf/seconddemo/Person.proto


服务端代码


package protobuf.seconddemo.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ProtoBufServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();

        try {
            //加载Initializer
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(parentGroup, childGroup)
                           .channel(NioServerSocketChannel.class)
                           .handler(new LoggingHandler(LogLevel.INFO))
                           .childHandler(new ProtoBufServerInitializer());

            //绑定监听端口
            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }
        finally {
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}

package protobuf.seconddemo.server;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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 protobuf.seconddemo.ModelInfo;

public class ProtoBufServerInitializer extends ChannelInitializer<SocketChannel>{
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //将字节数组转换成Person对象和将Person对象转成字节数组,一共需要四个处理器
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        pipeline.addLast(new ProtobufDecoder(ModelInfo.Person.getDefaultInstance()));
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(new ProtobufEncoder());

        //自定义处理器
        pipeline.addLast(new ProtoBufServerHandler());
    }
}

package protobuf.seconddemo.server;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import protobuf.seconddemo.ModelInfo;
import protobuf.seconddemo.ModelInfo.Person;

public class ProtoBufServerHandler extends SimpleChannelInboundHandler<ModelInfo.Person>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Person msg) throws Exception {
        System.out.println(msg.getName());
        System.out.println(msg.getAddress());
        System.out.println(msg.getAge());
    }
}


客户端代码



package protobuf.seconddemo.client;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ProtoBufClient {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //加载Initializer
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                           .channel(NioSocketChannel.class)
                           .handler(new ProtoBufClientInitializer());

            //连接服务端
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync();
            channelFuture.channel().closeFuture().sync();
        }
        finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}

package protobuf.seconddemo.client;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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 protobuf.seconddemo.ModelInfo;

public class ProtoBufClientInitializer extends ChannelInitializer<SocketChannel>{
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //将字节数组转换成Person对象和将Person对象转成字节数组,一共需要四个处理器
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        pipeline.addLast(new ProtobufDecoder(ModelInfo.Person.getDefaultInstance()));
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(new ProtobufEncoder());

        //自定义处理器
        pipeline.addLast(new ProtoBufClientHandler());
    }
}

package protobuf.seconddemo.client;



import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import protobuf.seconddemo.ModelInfo;
import protobuf.seconddemo.ModelInfo.Person;

public class ProtoBufClientHandler extends SimpleChannelInboundHandler<ModelInfo.Person>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Person msg) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ModelInfo.Person person = ModelInfo.Person.newBuilder()
                                                  .setName("Sam")
                                                  .setAddress("广州")
                                                  .setAge(34)
                                                  .build();

        ctx.writeAndFlush(person);
    }

}


运行代码


使用main方法分别启动服务端和客户端,当客户端与服务端建立连接的时候,将Person对象信息传递到服务端,服务端直接打印Person对象的信息。

客户端发送Person对象的代码
public class ProtoBufClientHandler extends SimpleChannelInboundHandler<ModelInfo.Person>{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ModelInfo.Person person = ModelInfo.Person.newBuilder()
                                                  .setName("Sam")
                                                  .setAddress("广州")
                                                  .setAge(34)
                                                  .build();

        ctx.writeAndFlush(person);
    }
}
服务端打印Person对象的代码
public class ProtoBufServerHandler extends SimpleChannelInboundHandler<ModelInfo.Person>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Person msg) throws Exception {
        System.out.println(msg.getName());
        System.out.println(msg.getAddress());
        System.out.println(msg.getAge());
    }
}

csdn code 路径


这个项目的源代码放置在csdn code上,欢迎访问。

netty_study

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值