美文网首页
protobufjs简单使用

protobufjs简单使用

作者: EasyNetCN | 来源:发表于2022-06-07 11:31 被阅读0次

    补充一下上一篇随笔 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))
    
    })
    

    相关文章

      网友评论

          本文标题:protobufjs简单使用

          本文链接:https://www.haomeiwen.com/subject/guqemrtx.html