netty学习七: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{
    @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{

    @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{
    @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{

    @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{
    @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{

    @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

CSDN博客稿源:CSDN博客 (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » netty学习七:netty集成protobuf完成数据序列化和反序列化

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录