Sam哥哥聊技术

互联网技术爱好者

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

阅读更多

扫码向博主提问

去开通我的Chat快问

linsongbin1

博客专家

熟悉互联网高并发系统架构设计
  • 擅长领域:
  • JAVA
  • 高并发系统架构设计
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linsongbin1/article/details/76856044
文章标签: java
个人分类: netty
所属专栏: netty
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭