利用protobuf格式进行前后端数据传输

创建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

    student = student_pb2.Student()

    student.SerializeToString()

前端用js:

    首先包含protobuf.js:

    加载.proto文件并进行反序列化:

     _utf2buffer = function(utfstr)
{
    var buf = new ArrayBuffer(utfstr.length);
    var bufView = new Uint8Array(buf);
    for (var i = 0, strlen = utfstr.length; i < strlen; i++) {
        bufView[i] = utfstr.charCodeAt(i);
    }
    return buf;
}
    
    var source = new EventSource("/datastream");
   
    source.onmessage = function(e) {
    //var message = new Uint8Array(e.data);
    var message = _utf2buffer(e.data)
    document.getElementById('htmlbody').innerHTML+=message+'
';
    console.log('message type:'+typeof(message));
    console.log(message);// do stuff based on received message 
    document.getElementById('htmlbody').innerHTML+="------------------------------------"+'
';
    //var showdata = protobuf.Reader.create(message);
    protobuf.load("/proto/student.proto", function(err, root) {
    if (err)
        throw err;
    var Student = root.lookup("Student");

    var showdata = Student.decode(new Uint8Array(message));

    console.log('show data:');
    document.getElementById('htmlbody').innerHTML+=showdata+'
';
    console.log(showdata);

 });
};
                       

 

 

你可能感兴趣的:(protobuf)