Unity技術(shù)博客 - 基于ProtoBuf協(xié)議實(shí)現(xiàn)網(wǎng)絡(luò)傳輸(上)

Unity版本: 5.3

使用語(yǔ)言: C#


寫(xiě)在前面

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中
  1. 創(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)書(shū)學(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()) {
                  //將消息寫(xiě)入流中
                  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;
              }
          }
      }
    

寫(xiě)在最后

 #成功的道路沒(méi)有捷徑,代碼這條路更是如此,唯有敲才是王道。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容