在网络通讯中应用Protobuf

在网络通讯中应用Protobuf

Protobuf的设计非常适用于在网络通讯中的数据载体,它序列化出来的数据量少再加上以K-V的方式来存储数据,对消息的版本兼容性非常强;还有一个比较大的优点就是有着很多的语言平台支持。下面讲解一下如何在TCP通讯应用中集成Protobuf.

     Protobuf提供一种简单的对象消息方式来描述数据的存储,通过相关实现可以简单地实现数据流和对象之间的转换。但由于Protobuf序列化后的信息并不包括一些相应对象类型描述,只有消息体的内容;因此在进行通信交互过程中默认情况是不知道这些数据和对象的对应关系;既然对方不清楚这些数据对应那种类型,那数据还源成对象就根本没办法入手。所以把Protobuf用到网络通讯中我们还需要外加一些协议来规范数据的对应关系。

     在通讯协议上只需要在消息体中先写入类型然后再写入Protobuf数据,TypeName主要是用于对方配匹数据对应的对象关系,这个TypeName是string还是int或其他就根据自己喜好来制定了。

     在通讯上问题就解决了,但还要面对实际中使用的一种情况消息太多了……那处理TypeName->Object则一个蛋痛的事情。还好在.net和android下有类元素表这玩意还能在运行行进行操作,从而可以大大节省这些if判断处理。由于本人熟悉的语言平台有限,在这里分别提供java和c#的解决方法。

  • Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void Register(Class<?> protobufclass) {
        try {
            ProtoMessageHandler mb;
            Class<?>[] protoObjs = protobufclass.getClasses();
            for (Class<?> item : protoObjs) {
                if(item==null)
                    continue;
                if (!item.isInterface() && item.getSuperclass().equals(
                        com.google.protobuf.GeneratedMessage.class)) {
                    mb = new ProtoMessageHandler();
                    mb.SetType(item);
                    mMessageTbl.put(item.getSimpleName(), mb);
                }
            }
        } catch (Exception e) {
             
             
        }
 
    }

     由于使用Protoc工具生成的类都会生成一个大类里,所以只需要注册指定的类然后对所有继承com.google.protobuf.GeneratedMessage的内嵌类找出来并记录在一个Map中即可。

1
2
3
4
5
String name= stream.ReadUTF();
        ProtoMessageHandler handler = ProtoPackage.GetMsgHandler(name);
        if(handler==null)
            throw new Exception(name+" message type notfound!");
        Message=(com.google.protobuf.GeneratedMessage) handler.GetObject(stream.GetStream());

     以上是通过类型值获取对应的对象,并填充Protobuf数据。

  • c#

     相对于android平台下的实现,.net的实现就更简单些了。

1
2
3
4
5
6
7
8
public static void Register(System.Reflection.Assembly assembly)
        {
            foreach(Type type in assembly.GetTypes())
            {
                if (!type.IsAbstract && !type.IsInterface && type.GetCustomAttributes(typeof(ProtoBuf.ProtoContractAttribute), false).Length > 0)
                    mProtoTbl[type.Name] = type;
            }
        }
1
2
3
string name = reader.ReadUTF();
            Type type = ProtoPakcage.GetProtoType(name);
            Message = ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(reader.Stream, null, type);

     通过以上方法在使用Protobuf的时候就不用担心消息太多写if写到手软了,也不容易出错。不过有一点要注意的就是类的名称一定要对应,否则就无法匹配到消息了。如果想得到完全整的代码可以到https://beetlenp.codeplex.com获取。

原文地址:https://www.cnblogs.com/Leo_wl/p/3287779.html