码迷,mamicode.com
首页 > Web开发 > 详细

Netty集成Protobuf与多协议消息传递

时间:2019-08-10 21:39:10      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:field   ima   finally   override   exception   frame   erb   日志   channel   

一、创建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:\workspace\study\basic\netty_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、服务端输出

技术图片

 

Netty集成Protobuf与多协议消息传递

标签:field   ima   finally   override   exception   frame   erb   日志   channel   

原文地址:https://www.cnblogs.com/linlf03/p/11332765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!