Unity版本: 5.3
使用語言: C#
寫在前面
ProtoBuf是Google公司推出的一種二進(jìn)制序列化工具竞漾,適用于數(shù)據(jù)的網(wǎng)絡(luò)傳輸吨岭。
基于Socket實(shí)現(xiàn)時(shí)時(shí)通信休溶,關(guān)于數(shù)據(jù)粘包的編碼和解碼處理是必不可少的府阀。
實(shí)現(xiàn)功能:
1.基于ProtoBuf序列化對(duì)象
2.使用Socket實(shí)現(xiàn)時(shí)時(shí)通信
3.數(shù)據(jù)包的編碼和解碼
1.Unity中使用ProtoBuf
- 導(dǎo)入DLL到Unity中
-
創(chuàng)建網(wǎng)絡(luò)傳輸?shù)哪P皖?/p>
using System; using ProtoBuf; //添加特性沫换,表示可以被ProtoBuf工具序列化 [ProtoContract] public class NetModel { //添加特性臭蚁,表示該字段可以被序列化,1可以理解為下標(biāo) [ProtoMember(1)] public int ID; [ProtoMember(2)] public string Commit; [ProtoMember(3)] public string Message; }
-
在Unity中添加測(cè)試腳本讯赏,介紹ProtoBuf工具的使用垮兑。中間用到了流這個(gè)概念,對(duì)于此概念不熟悉的同學(xué)先去我的簡(jiǎn)書學(xué)習(xí)漱挎。
using System; using System.IO; public class Test : MonoBehaviour { void Start () { //創(chuàng)建對(duì)象 NetModel item = new NetModel(){ID = 1, Commit = "LanOu", Message = "Unity"}; //序列化對(duì)象 byte[] temp = Serialize(item); //ProtoBuf的優(yōu)勢(shì)一:小 Debug.Log(temp.Length); //反序列化為對(duì)象 NetModel result = DeSerialize(temp); Debug.Log(result.Message); } /// <summary> /// 將消息序列化為二進(jìn)制的方法 /// </summary> /// <param name="model">要序列化的對(duì)象</param> private byte[] Serialize(NetModel model) { try { //涉及格式轉(zhuǎn)換系枪,需要用到流,將二進(jìn)制序列化到流中 using (MemoryStream ms = new MemoryStream()) { //使用ProtoBuf工具的序列化方法 ProtoBuf.Serializer.Serialize<NetModel> (ms, model); //定義二級(jí)制數(shù)組磕谅,保存序列化后的結(jié)果 byte[] result = new byte[ms.Length]; //將流的位置設(shè)為0私爷,起始點(diǎn) ms.Position = 0; //將流中的內(nèi)容讀取到二進(jìn)制數(shù)組中 ms.Read (result, 0, result.Length); return result; } } catch (Exception ex) { Debug.Log ("序列化失敗: " + ex.ToString()); return null; } } /// <summary> /// 將收到的消息反序列化成對(duì)象 /// </summary> /// <returns>The serialize.</returns> /// <param name="msg">收到的消息.</param> private NetModel DeSerialize(byte[] msg) { try { using (MemoryStream ms = new MemoryStream()) { //將消息寫入流中 ms.Write (msg, 0, msg.Length); //將流的位置歸0 ms.Position = 0; //使用工具反序列化對(duì)象 NetModel result = ProtoBuf.Serializer.Deserialize<NetModel> (ms); return result; } } catch (Exception ex) { Debug.Log("反序列化失敗: " + ex.ToString()); return null; } } }
寫在最后
#成功的道路沒有捷徑,代碼這條路更是如此膊夹,唯有敲才是王道衬浑。