ProtoBuf与网络通信——英雄联盟

1,protobuf全称Protocol Buffers,是一种二进制的数据格式,具有更高的传输,打包和解包效率

2,protobuf的IDL都是保存为*.proto的文件中

3,proto文件中数据类型可以分为两大类复合数据类型标准数据类型复合数据类型包括:枚举message类型标准数       数据类型包含:整型,浮点,字符串等

最常用的数据格式就是message,message会对应生成一个class


message Order
{
    required uint64 uid = 1;
    required float cost = 2;
    optional string tag = 3;
}

required: 必须赋值,不能为空

optional:字段可以赋值,也可以不赋值。

4,BSToGC类:

      AskGateAddressRet为一个结构体,变成类的形式可以取里面的mgsid

5,protobuf.net  下载   GitHub   

所有的更新都在这



 NetworkManager.Instance.Update(Time.deltaTime);//实时监听网络消息的发送和接受

CGLCtrl_GameLogic类:

     GameCompleteBaseInfo方法,客户端发送给服务器


 对这个消息结构体填充

 GCToCS.CompleteInfo pMsg = new GCToCS.CompleteInfo
       {
           nickname = System.Text.Encoding.UTF8.GetString(nickName),   //ToReview 字符串重复编码解码,需写一个测试确定是否必要
           headid = headerID,
           sex = sex                                                   //ToReview byte->int
       };
NetworkManager.Instance.SendMsg(pMsg, (int)pMsg.msgnum)   //方法发送出去 
     ProtoBuf.Serializer.Serialize(mSendStream, pMsg);                
     CMsg pcMsg = new CMsg((int)mSendStream.Length); 

pcMsg.SetProtocalID(n32MsgID);   
            pcMsg.Add(mSendStream.ToArray(), 0, (int)mSendStream.Length);//放入到队列中


    以上代码为Protobuf的序列化



CGLCtrl_GameLogic_MsgHandler 类   :

     接受消息需要每一帧去判断是否手收到,

     HandleNetMsg方法    负责处理服务器发送给客户端的消息;

  CGLCtrl_GameLogic.Instance.HandleNetMsg(iostream, type);//处理网络消息

 通过消息的ID去区分   服务器发过来的是什么消息


对接受消息进行处理进行处理

 Int32 OnNetMsg_NotifyPing(Stream stream)
    {
        GSToGC.PingRet pMsg;
        if (!ProtoDes(out pMsg, stream))
        {
            return PROTO_DESERIALIZE_ERROR;
        }
        Int64 n64NowTime = CGLCtrl_GameLogic.Instance.GetNowTime();
        float ping = CGLCtrl_GameLogic.Instance.GetDuration(n64NowTime, pMsg.time);
        if (pMsg.flag == 0)
        {
            ShowFPS.Instance.cSPing = ping;
        }
        else
        {
            ShowFPS.Instance.sSPing = ping;
            CEvent eve = new CEvent(EGameEvent.eGameEvent_SSPingInfo);
            eve.AddParam("ping", ping);
            EventCenter.SendEvent(eve);
        }
        return (Int32)EErrorCode.eNormal;
    }
 //封装proto解析
    private bool ProtoDes<T>(out T pMsg, Stream stream)
    {
        try
        {
            pMsg = ProtoBuf.Serializer.Deserialize<T>(stream);
            if (null == pMsg)
            {
                Debug.LogError("Proto解析为Null");
                pMsg = default(T);
                return false;
            }
            return true;
        }
        catch (Exception)
        {
            Debug.LogError("Proto解析异常");
            pMsg = default(T);
            return false;
        }
    }


猜你喜欢

转载自blog.csdn.net/qq_35647121/article/details/80962135