创建student.proto文件,格式如下:
1 syntax = "proto3";
2 message Student{
3 int64 id = 1;
4 string name = 2;
5 int64 age = 3;
6 }
后端用python:
通过protoc将.proto文件生成XX_pb2.py文件,然后import使用,在后端对.proto文件中变量进行赋值,然后对数据进行序列化SerializeToString()
: serializes the message and returns it as a string. Note that the bytes are binary, not text; we only use the str
type as a convenient container.
生成命令:protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/XXX.proto
创建对象:student = student_pb2.Student()
为对象的各个变量赋值:
def set_student():
student.id = 8
student.name = 'Sally'
student.age = 17
前端用js:
首先包含protobuf.js:<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.8.8/dist/protobuf.js"></script>
加载.proto文件并进行反序列化:
protobuf.load("student.proto", function(err, root) {
if (err)
throw err;
var student = root.lookup("Student");
var stu = Student.creat({id:1,name:"Andy",age:20}) ;//在前端进行变量赋值
var buffer = Student.encode(stu).finish();//在前端进行序列化
var showdata = Student.decode(buffer);//在前端进行反序列化