0
点赞
收藏
分享

微信扫一扫

Netty:使用protobuf传递多种类型数据

笙烛 2022-02-13 阅读 30
java

1.定义消息.proto文件

syntax="proto3";
package test;
option java_package="cn.edu.tju";
option java_outer_classname="MyData";

message Being{

enum DataType{
PersonType=0;
CatType=1;
DogType=2;
}
DataType data_type=1;

oneof dataBody{
Person person=2;
Cat cat=3;
Dog dog=4;
}

}
message Person{
string name=1;
int32 age=2;
}
message Cat{
string name=1;
int32 age=2;
}
message Dog{
string name=1;
int32 age=2;
}

2.修改server

package cn.edu.tju;

import cn.edu.tju.handler.ObjectServerHandler;
import cn.edu.tju.handler.ObjectServerHandler2;
import cn.edu.tju.handler.ObjectServerHandler3;
import cn.edu.tju.nt.SubscribeReqProto;
import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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;

public class NettyServer2 {
    private static int port=9095;
    public static void main(String[] args) {
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                            channel.pipeline().addLast(new ProtobufDecoder(MyData.Being.getDefaultInstance()));
                            channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                            channel.pipeline().addLast(new ProtobufEncoder());
                            channel.pipeline().addLast(new ObjectServerHandler2());


                        }
                    });
            ChannelFuture channelFuture=serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();




        }catch (Exception ex){

        }

    }
}

举报

相关推荐

0 条评论