CocosCreator中protobuf与js对象互转
在项目中使用protobuf的时候,各个变量赋值写起来很累。最好的方式是传一个js的结构体,自动转换为pb的对应方法
1. 添加protobuf支持
- npm install google-protobuf
2. 测试的proto文件,内容如下:
`syntax = “proto3”;
package Login;
option go_package = “proto/Login”;
//消息互动
message Message {
string Type = 1; //方法名
bytes Datas = 2; //消息内容
}
//登陆游戏
message LoginGet{
sint32 UserID = 1;
string Key = 2;
sint32 GameID = 3;
repeated sint32 Thirds = 4;
map<int32, int32> Maps = 5;
}
message LoginAck{
sint32 CRet = 1;
sint32 UserID = 2;
}`
- 客户端与服务器的数据交互可以使用Message,传报名+方法名。比如:Login.LoginGet
- LoginGet中定义了基本的类型,结构体也支持
3. 发送代码如下:
`let obj = {
UserID: 111,
Key: “userkey”,
GameID: 1001,
Thirds: [1,2,3,4,5,6,7,8],
Maps: {1:1, 2:2, 3:3},
}
console.log(“发送数据:”, obj)
let senddata = this.encodeData(“Login.LoginGet”, obj)`
-
解析代码如下:
`
decodeData : function (_key, _data){
let array = _key.split(“.”)
if (array.length<2){
cc.log(“error:”, _key, _data)
return
}
if (window[array[0]] && window[array[0]][array[1]]){
let pbc = window[array[0]][array[1]].deserializeBinary(_data)
let obj = pbc.toObject()
this.dispatch(array[0], array[1], obj)
} else {
cc.log(“error none obj:”, _key, _data)
}
},
//解析数据
let result = this.decodeData(“Login.LoginGet”, senddata)
console.log(“收到数据:”, result)
`
-
效果截图: