在網絡通信中應用Protobuf

     Protobuf的設計很是適用於在網絡通信中的數據載體,它序列化出來的數據量少再加上以K-V的方式來存儲數據,對消息的版本兼容性很是強;還有一個比較大的優勢就是有着不少的語言平臺支持。下面講解一下如何在TCP通信應用中集成Protobuf. java

     Protobuf提供一種簡單的對象消息方式來描述數據的存儲,經過相關實現能夠簡單地實現數據流和對象之間的轉換。但因爲Protobuf序列化後的信息並不包括一些相應對象類型描述,只有消息體的內容;所以在進行通訊交互過程當中默認狀況是不知道這些數據和對象的對應關係;既然對方不清楚這些數據對應那種類型,那數據還源成對象就根本沒辦法入手。因此把Protobuf用到網絡通信中咱們還須要外加一些協議來規範數據的對應關係。 android

     在通信協議上只須要在消息體中先寫入類型而後再寫入Protobuf數據,TypeName主要是用於對方配匹數據對應的對象關係,這個TypeName是string仍是int或其餘就根據本身喜愛來制定了。 git

     在通信上問題就解決了,但還要面對實際中使用的一種狀況消息太多了……那處理TypeName->Object則一個蛋痛的事情。還好在.net和android下有類元素表這玩意還能在運行行進行操做,從而能夠大大節省這些if判斷處理。因爲本人熟悉的語言平臺有限,在這裏分別提供java和c#的解決方法。 github

  • Java
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中便可。 c#

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的實現就更簡單些了。 工具

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;
            }
        }
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獲取。 google

我的站:www.ikende.com spa

我的開源項目github.com/IKende

elastic communication component for .net .net

相關文章
相關標籤/搜索