赞
踩
pbjs -t static-module -w commonjs -o proto.js *.proto
syntax = "proto3";
package grace.proto.msg;
message Person {
string id = 1;
string name = 2;
string email = 3;
}
//测试protobuf数据的接口 @PostMapping("/protobuf") public String getProtoBuf(@RequestParam(value = "id", defaultValue = "") String str){ try { // //数据封装 // //获取Person对象 // Protos.UserCache.Builder builder = Protos.UserCache.newBuilder(); // //通过person的内部类builder提供了构建相关属性的set方法 // builder.setUID(1); // builder.setName("张三"); // builder.setHead(1); // //序列化对象 // Protos.UserCache person = builder.build(); // System.out.print("数据大小"+person.toByteString().size()+"\n"); //数据拆分 System.out.print("打印传递参数111:"+str+"\n"); byte[] bytes = Base64.getDecoder().decode(str); System.out.print("数据为222:"+bytes+"\n"); PersonMsg.Person p = null; try { p = PersonMsg.Person.parseFrom(bytes); System.out.print("数据为333:"+p.getId()+"\n"); System.out.print("数据为444:"+p.getName()+"\n"); System.out.print("数据为555:"+p.getEmail()+"\n"); }catch (InvalidProtocolBufferException e){ System.out.print("异常为:"+e+"\n"); } return String.valueOf(str); }catch (Exception e){ return e.toString(); } }
Java端打印数据:
打印传递参数111:CgExEgblvKDkuIkaDOS4jeWRiuivieS9oA==
数据为222:[B@77b050f4
数据为333:1
数据为444:张三
数据为555:不告诉你
onLoad() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { // console.log("aaa结束了", xhr.responseText); //获取到后台传递过来的protobuf字符串 // var nnnn = xhr.responseText; }; let protobuf = require("protobuf"); let protores = require("proto"); var msgType = protores.grace.proto.msg.Person; //封装数据 var d = { id: "1", name: "张三", email: "不告诉你" }; var msg = msgType.create(d); var bytes = msgType.encode(msg).finish(); cc.log("msg: ", msg); cc.log("bytes: ", bytes); //封装 var b64 = protobuf.util.base64.encode(bytes, 0, bytes.length); cc.log("b64: ", b64); 拆分数据 // var msg = msgType.decode(b64); // var data = msgType.toObject(msg, { // longs: Number, //long默认转换为Number类型 // enums: String, // bytes: String // // see ConversionOptions // }); // cc.log("data: ", data); xhr.open("POST", "http://127.0.0.1:8888/test/protobuf?id=" + b64, true); xhr.send(); console.log("======================"); }
CocosCreator打印数据:
尝试了很多代码,只有这个转的可用,其他不适报错就不变
var b64 = protobuf.util.base64.encode(bytes, 0, bytes.length);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。