js 使用protobuf

之前写过node使用protobuf,这个算是综合一点吧。也涉及到前端页面的对protobuf的使用.

google官方的ProtoBuf
  • Protocol Buffers ,下载对应的版本,然后将路径加入环境变量,在终端输入protoc 出现下面即可:
    在这里插入图片描述

  • 添加proto文件:proto_person.proto,然后再终端对于目录下输入: protoc --js_out=import_style=commonjs,binary:. .\proto_person.proto 则会生成对应的文件:proto_person_pb.js
    protoc使用

syntax = "proto3";
package properson;

message Person {
  string Name = 1;
  int32 Age = 3;
}
node使用
  • 如果是node使用,则已经可以直接引用了,首先需要添加google-protobuf的包引用。新建package.json,添加依赖。执行 npm install
"dependencies": {
        "google-protobuf": "3.6.0"
    }
  • 新建main.js 添加:
var pb = require('./proto_person_pb');

var p = new pb.Person();
p.setName("Tom");
p.setAge(18);

var bytes = p.serializeBinary();

var unBytes = pb.Person.deserializeBinary(bytes);

var name = p.getName();
var age = p.getAge();

console.log(bytes);
console.log(unBytes);
console.log("==================================");
console.log("my name is ", name, "age is", age);
  • 执行 node main.js 即可看到输出:
Uint8Array [ 10, 3, 84, 111, 109, 24, 18 ]
{ wrappers_: null,
  messageId_: undefined,
  arrayIndexOffset_: -1,
  array: [ 'Tom', <1 empty item>, 18 ],
  pivot_: 1.7976931348623157e+308,
  convertedFloatingPointFields_: {} }
==================================
my name is  Tom age is 18
js 前端的使用
  • 安装包:
npm install -g require
npm install -g browserify
  • 使用browserify对文件进行编译打包

    • 编写脚本保存为exports.js
    var personProto = require('./proto_person_pb.js');
    module.exports = {
         DataProto: personProto
    }
    
    • 执行命令 browserify exports.js > person.js 将proto_person_pb.js文件进行编译打包生成person.js
    • 编写html:index.html,测试。
     <html>
        <head>
       	 <script src="./person.js"></script>
       	    <script>
      			  var p = new proto.properson.Person();
      			 p.setName("Tom");
      			 p.setAge(18);
      			 var bytes = p.serializeBinary();
       		     var unBytes = proto.properson.Person.deserializeBinary(bytes);
       		     var name = p.getName();
       		     var age = p.getAge();
    
      			 console.log(bytes);
       		     console.log(unBytes);
       		     console.log("==================================");
      			 console.log("my name is ", name, "age is", age);
     		 </script>
       </head>
    </html>  
    
    • 然后在浏览器中打开index.html,打开调试模式的console可以看到:

    在这里插入图片描述

protobuf.js 使用
  • 安装包: protobuf.js 。官方网址
    npm install -g protobufjs -g 代表全局安装,需要使用pbjs工具。
  • 本目录安装protobufjs,在package.json中的dependencies节点添加 :“protobufjs”: “6.8.8”,使用6.8.8版本
node 端使用
  • protobufjs可以直接反射proto文件,所以这一步不需要生成任何文件。还是刚才的proto文件,在刚才的main.js中写入:(注意路径)
var protobuf = require("protobufjs");

protobuf.load("./proto_person.proto", function (err, root) {
 if (err)
     throw err;

 // Obtain a message type
 var AwesomeMessage = root.lookupType("properson.Person");

 // Exemplary payload
 var payload = { Name: "Tom", Age: 18 };

 // Verify the payload if necessary (i.e. when possibly incomplete or invalid)
 var errMsg = AwesomeMessage.verify(payload);
 if (errMsg)
     throw Error(errMsg);

 // Create a new message
 var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary

 // Encode a message to an Uint8Array (browser) or Buffer (node)
 var buffer = AwesomeMessage.encode(message).finish();
 // ... do something with buffer

 // Decode an Uint8Array (browser) or Buffer (node) to a message
 var message = AwesomeMessage.decode(buffer);
 console.log(message)
 // ... do something with message
});
  • 执行node main.js 即可看到:
Person { Name: 'Tom', Age: 18 }
  • 利用pbjs 生成js 使用,在终端输入: pbjs -t static-module -w commonjs -o person_proto.js .\proto_person.proto 生成person_proto.js文件
    +在main.js 中输入:

var protobuf = require("./person_proto");

// Obtain a message type
var p = protobuf.properson.Person;

// Exemplary payload
var payload = { Name: "Tom", Age: 18 };

// Verify the payload if necessary (i.e. when possibly incomplete or invalid)
var errMsg = p.verify(payload);
if (errMsg)
throw Error(errMsg);

// Create a new message
var message = p.create(payload); // or use .fromObject if conversion is necessary

// Encode a message to an Uint8Array (browser) or Buffer (node)
var buffer = p.encode(message).finish();
// ... do something with buffer

// Decode an Uint8Array (browser) or Buffer (node) to a message
var message = p.decode(buffer);
console.log(message)
// ... do something with message
js 前端使用
<html>

<head>
    <!-- <script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.8.8/dist/protobuf.js"></script> -->
    <script src="./protobuf.js"></script>

    <script>
        protobuf.load("./proto_person.proto", function (err, root) {
            if (err)
                throw err;

            // Obtain a message type
            var p = root.lookupType("properson.Person");

            // Exemplary payload
            var payload = { Name: "Tom", Age: 18 };

            // Verify the payload if necessary (i.e. when possibly incomplete or invalid)
            var errMsg = p.verify(payload);
            if (errMsg)
                throw Error(errMsg);

            // Create a new message
            var message = p.create(payload); // or use .fromObject if conversion is necessary

            // Encode a message to an Uint8Array (browser) or Buffer (node)
            var buffer = p.encode(message).finish();
            // ... do something with buffer

            // Decode an Uint8Array (browser) or Buffer (node) to a message
            var message = p.decode(buffer);
            console.log(message)
            // ... do something with message
        });
    </script>
</head>

<body>
    <h3>protobuf test</h3>
</body>

</html>
  • 打开浏览器调试默认,在console端可看到:
    在这里插入图片描述
js 前端对js文件的解析

protobuf.js 虽然可以生成js文件,但是好像不能用于前端页面,估计也是需要用browserify转化,具体没试过。如有知道protobuf.js生成js直接用于前端的,希望可以互相学习一下。

注: 另外pbjs 也可生成json文件用于交互,具体可以看官方的教程。

  • 4
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值