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编码