http://blog.csdn.net/janeky/article/details/17104877程序員
個遊戲包含了各類數據,包括本地數據和與服務端通訊的數據。今天咱們來談談如何存儲數據,以及客戶端和服務端的編碼方式。根據之前的經驗,咱們能夠用字符串,XML,json...甚至能夠直接存儲二進制。各類方式都有各自的優劣,有些性能比較好,可是實現方式比較麻煩。有些數據冗餘太多。編程
今天咱們來學習一種普遍使用的數據格式:Protobuf。簡單來講,它就是一種二進制格式,是google發起的,目前普遍應用在各類開發語言中。具體的介紹能夠參見:https://code.google.com/p/protobuf/ 。咱們之因此選擇protobuf,是基於它的高效,數據冗餘少,編程簡單等特性。關於C#的protobuf實現,網上有好幾個版本,公認比較好的是Protobuf-net。
json
先來看一個最簡單的例子:把一個類用Protobuf格式序列化到一個二進制文件。再讀取二進制數據,反序列化出對象數據。ide
從網上參考了一個例子 http://blog.csdn.net/ddxkjddx/article/details/7239798性能
//----------------實體類----------------------學習
- using UnityEngine;
- using System.Collections;
- using ProtoBuf;
- using System;
- using System.Collections.Generic;
-
-
- [ProtoContract]
- public class Test {
-
-
- [ProtoMember(1)]
- public int Id
- {
- get;
- set;
- }
-
-
- [ProtoMember(2)]
- public List<String> data
- {
- get;
- set;
- }
-
-
- public override string ToString()
- {
- String str = Id+":";
- foreach (String d in data)
- {
- str += d + ",";
- }
- return str;
- }
-
- }
//-----------測試類---------------------------測試
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using ProtoBuf;
- using System;
-
-
- public class ProtobufNet : MonoBehaviour {
-
-
- private const String PATH = "c://data.bin";
-
-
- void Start () {
-
- List<Test> testData = new List<Test>();
- for (int i = 0; i < 100; i++)
- {
- testData.Add(new Test() { Id = i, data = new List<string>(new string[]{"1","2","3"}) });
- }
-
- using(Stream file = File.Create(PATH))
- {
- Serializer.Serialize<List<Test>>(file, testData);
- file.Close();
- }
-
- List<Test> fileData;
- using (Stream file = File.OpenRead(PATH))
- {
- fileData = Serializer.Deserialize<List<Test>>(file);
- }
-
- foreach (Test data in fileData)
- {
- Debug.Log(data);
- }
- }
-
- }
Protobuf-net 利用Attributes來實現序列化字段,對程序員的負擔減輕,代碼侵入性也下降。接下來,我將會寫一個簡單的Unity c/s demo,其中的通訊編碼就是用到Protobuf,google
到時再與你們分享。有任何問題歡迎一塊兒探討ken@iamcoding.com編碼