Unity配置Protobuf协议

Protobuf的强大我就不多介绍了,问度娘,会有很多说明的,今天配置了一下Unity里使用Protobuf,  

写.proto文件: 

ID文件:

enum MSGID
{ 	
	CSID_C2L_LOGINSERVER 		= 1020; //请求登陆
	CSID_L2C_LOGINSERVER		= 1021; //返回登陆结果  
}

Data文件:  
message MSG_C2L_LOGINSERVER
{
	 required string account = 1;  //账号
	 required string password = 2; //密码
}
message MSG_L2C_LOGINSERVER
{
	required int32 ret = 1;	//0成功,否则为错误号
}

接着使用工具生成C#代码文件,工具怎么生成,哪里来的,我就略过了,这里提供下载地址: Protobuf编译C++和C#文件


把生成出来的C#文件拷贝的工程目录下,再把Google.ProtocolBuffers.dll(在Protobuf编译C++和C#文件包里有)拷贝到工程的dll目录下面,重新编译,

重新打开VS,可以看到VS工程引用下面有Google.ProtocolBuffers就说明没有问题。


最后就是调用,代码如下:

        //声明
        DotaMsgData.MSG_C2L_LOGINSERVER.Builder msgLogin = new DotaMsgData.MSG_C2L_LOGINSERVER.Builder();
        msgLogin.SetAccount("test");
        msgLogin.SetPassword("123456");

        //使用Google.ProbobufBuffes
        IMessage msg = msgLogin.Build();

        //转成流
        MemoryStream sendstream = new MemoryStream();
        msg.WriteTo(sendstream);


解包参考之前的一段代码:

    public T StreamToMsg<T>(MemoryStream ms) where T : class, IMessage
    {
        Type type = typeof(T);

        g_obj.SetValue(ms.ToArray(), 0);

        MethodInfo method = type.GetMethod("ParseFrom", g_types);

        return (T)method.Invoke(null, g_obj);
    }

    private object[] g_obj = new object[1];

    private static Type[] g_types = new Type[] { typeof(byte[]) };

然后调用上面那个函数:

        DotaMsgData.MSG_C2L_LOGINSERVER msgpre = StreamToMsg<DotaMsgData.MSG_C2L_LOGINSERVER>(sendstream);

        Debug.Log("ParseRet, pssword: " + msgpre.Password);
        Debug.Log("ParseRet, account: " + msgpre.Account); 


从上面可以看出,Protobuf在C#中的写法和C++中的写法不太一样, C#里面需要通过DotaMsgData.MSG_C2L_LOGINSERVER.Builder来处理对象。


上面的方法只能在安卓和pc上面用,如果想要在ios上用的话可以参考下面这种方法

生成Dll的方式放入工程调用,参考资料:在ios android设备上使用 Protobuf (使用dll方式)

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值