• Netty集成Protobuf


    一、创建Personproto.proto

    创建Personproto.proto文件

    syntax = "proto2";
    
    package com.example.protobuf;
    
    option optimize_for = SPEED;
    option java_package = "com.example.sixthexample";
    option java_outer_classname = "MyDataInfo";
    
    message Person{
        required string name = 1;
        optional int32 age = 2;
        optional string address = 3;
    
    }
    

      

    2、重新生成

    D:workspacestudyasic etty_demo>protoc --java_out=src/main/java  src/protobuf/Person.proto

    二、创建Netty服务端代码

    1、TestServer 类

    public class TestServer {
    
        public static void main(String[] args) throws  Exception{
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try{
    
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.INFO)) //增加日志处理器
                        .childHandler(new TestServerInitializer());
    
                ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
                channelFuture.channel().closeFuture().sync();
            }finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    

      

    2、TestServerHandle类

    public class TestServerHandle extends SimpleChannelInboundHandler<MyDataInfo.Person> {
    
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.Person msg) throws Exception {
            System.out.println("---- 服务端接收到消息 ----");
            System.out.println(msg.getName());
            System.out.println(msg.getAge());
            System.out.println(msg.getAddress());
        }
    }
    

      

    3、TestServerInitializer 类

    public class TestServerInitializer extends ChannelInitializer<SocketChannel>{
    
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline pipeline = socketChannel.pipeline();
            pipeline.addLast(new ProtobufVarint32FrameDecoder());
            pipeline.addLast(new ProtobufDecoder(MyDataInfo.Person.getDefaultInstance()));
            pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
            pipeline.addLast(new ProtobufEncoder());
    
            pipeline.addLast(new TestServerHandle());
        }
    }
    

      

    三、创建客户端代码

    1、TestClient 类

    public class TestClient {
    
        public static void main(String[] args) throws  Exception{
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            try {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                        .handler(new TestClientInitializer());
    
                ChannelFuture channelFuture = bootstrap.connect("localhost",8899).sync();
                channelFuture.channel().closeFuture().sync();
    
            }finally {
                eventLoopGroup.shutdownGracefully();
            }
        }
    }
    

      

    2、TestClientHandle 类

    public class TestClientHandle extends SimpleChannelInboundHandler<MyDataInfo.Person> {
    
        // 对于客户端来说,输入来自控制台
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.Person msg) throws Exception {
    
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            //客户端启动后,将消息发送给服务端
            MyDataInfo.Person person = MyDataInfo.Person.newBuilder()
                     .setName("张三").setAge(30).setAddress("上海").build();
             ctx.channel().writeAndFlush(person);
        }
    }
    

      

    3、TestClientInitializer 类

    public class TestClientInitializer extends ChannelInitializer<SocketChannel> {
    
    
    
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new ProtobufVarint32FrameDecoder());
            pipeline.addLast(new ProtobufDecoder(MyDataInfo.Person.getDefaultInstance()));
            pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
            pipeline.addLast(new ProtobufEncoder());
            pipeline.addLast(new TestClientHandle());
        }
    }
    

      

    四、测试

    1、启动服务端

    2、启动客户端

    3、服务端输出

  • 相关阅读:
    centos7 yum 安装mariadb
    curl 获取外网IP
    ansible之一:安装与配置
    第一步 django的下载安装
    命名空间的三种引用方式:非限定名称、限定名称、完全限定名称
    重温PHP之快速排序
    PHP实现文件下载的核心代码
    PHP常量定义之define与const对比
    ThinkPHP中I('post.')与create()方法的对比
    重温PHP之选择排序
  • 原文地址:https://www.cnblogs.com/linlf03/p/11332765.html
Copyright © 2020-2023  润新知