Mecanim 发表于 2022-6-8 14:24

protobufjs简单使用

补充一下上一篇随笔 https://www.jianshu.com/p/563251694182 的一点内容:一定要用google.golang.org/protobuf/proto全部替换github.com/gogo/protobuf/proto,假如不替换,是服务正常解析protobuf的。

protobufjs(https://github.com/protobufjs/protobuf.js)可以让我们再浏览器中使用protobuf,下面的例子是如何在普通页面中,直接使用protobufjs。

全局安装protobufjs,使用pbjs直接生成proto文件对应的js protobuf描述文件,这样就可以在普通页面中直接使用了。
var root = protobuf.Root.fromJSON({    "nested": {      "protocol": {            "options": {                "go_package": "/protocol"            },            "nested": {                "Message": {                  "fields": {                        "fromUsername": {                            "type": "string",                            "id": 1                        },                        "from": {                            "type": "string",                            "id": 2                        },                        "to": {                            "type": "string",                            "id": 3                        },                        "content": {                            "type": "string",                            "id": 4                        },                        "contentType": {                            "type": "int32",                            "id": 5                        },                        "type": {                            "type": "string",                            "id": 6                        },                        "messageType": {                            "type": "int32",                            "id": 7                        },                        "fileKey": {                            "type": "string",                            "id": 8                        },                        "fileSuffix": {                            "type": "string",                            "id": 9                        },                        "file": {                            "type": "bytes",                            "id": 10                        }                  }                }            }      }    }});let messageProto = root.lookup("protocol.Message")let reader = new FileReader();reader.readAsArrayBuffer(message.data);reader.onload = ((event) => {    let messagePB = messageProto.decode(new Uint8Array(event.target.result))})
页: [1]
查看完整版本: protobufjs简单使用