详解vue中使用protobuf踩坑记

所属分类: 网络编程 / JavaScript 阅读数: 1190
收藏 0 赞 0 分享

官方解释为:

Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the "old" format.

翻译是(机翻---我英语不好)

协议缓冲区是用于序列化结构化数据的灵活,高效的自动化机制 - 思考XML,但更小,更快,更简单。您可以定义一次数据的结构,然后您可以使用特殊的源代码轻松地将结构化数据写入各种数据流并使用各种语言读取和读取数据。您甚至可以更新您的数据结构,而不会中断根据“旧”格式编译的已部署程序。

特点:

  • 更简单
  • 是3到10倍小
  • 速度要快20到100倍
  • 不太模糊
  • 生成更易于以编程方式使用的数据访问类

代码

在github上写了个demo demo地址 有需要的可以下载下来跑一下就理解了。PS:如果觉得有用 请给我个小星星 (笔芯~)

使用

其实最开始我尝试使用一个第三方JSprotobuf.js protobuf.load 的时候浏览器报了个错illegal token '<' (/demo.proto, line 1) 查找了下官网issue,大意应该是proto文件多了个字符,但是我查看过proto文件并没有发现有多的'<',怎么办呢,最后放弃使用第三方。用官方提供的方法。

下载protobuf编译器

下载地址 (我下载的是3.40版) github也提供了zip包,可自行下载 (目前最新版本是v3.6.0) 用来编译proto为JS文件方便调用

配置环境变量

由于公司用的是win10 只需要将下载的文件地址添加到path即可 Mac与window命令唯一的区别就是需要将protoc改成protoc.exe 前提是需要添加环境变量

编写proto文件

为了确保前后一致,下面是后台写给我的一个测试proto,我司后台是java

syntax = "proto2";//protobuf版本
option java_package = "com.test.protobuf";
option java_outer_classname = "PersonMessage";
message Person {
 required int32 id = 1;
 optional string name = 2;
 optional string email = 3;
 repeated string list = 4;
 extensions 100 to 1000;//允许扩展的ID
}

message PersonTree {
 optional string id = 1;
 optional string title = 2;
 repeated PersonTree childs = 3;
}

extend Person {
 optional int32 count = 101;
 optional int32 likes_cnt= 102;
}

message PersonEx {
 optional int32 id = 1;
 extend Person {
  optional int32 px = 103;
  optional int32 py= 104;
 }
 optional Person p = 2;
}

使用vue-cli构建一个工程目录

npm install -g vue-cli
vue init webpack my-project
cd my-project
npm install
npm run dev

安装插件: npm install axios element-ui google-protobuf --save

编译proto为JS

进入 awesome.proto 的存放路径 使用如下命令 protoc.exe --js_out=import_style=commonjs,binary:. awesome.proto

  • 会生成一个awesome_pb.js文件
  • 点击查看awesome_pb.js其实可以看到里面是生成好的方法。只需要在页面中引入JS调用即可

之后我们将这个文件引入页面,当然你也可以考虑全局引用

测试

本地测试

编写一个测试页面,创建一个测试按钮 我是在测试页面 import messages from './awesome_pb.js' 方法为:

methods: {
  protobufferTest () {
   var message = new messages.Person() // 调用Person对象 实例化
   // 赋值
   message.setId(23)
   message.setName('asd')
   // 序列化
   var bytes = message.serializeBinary()

   console.log(bytes) // Uint8Array(7) [8, 23, 18, 3, 97, 115, 100]

   // 反序列化
   var message2 = messages.Person.deserializeBinary(bytes)

   console.log(message2) // proto.PersonTree {wrappers_: null, messageId_: undefined, arrayIndexOffset_: -1, array: Array(3), pivot_: 1.7976931348623157e+308, …}

  }
 }

到此,本地测试完成,没什么毛病了。

前后端联调测试

前方有坑

前后传输是使用的FormData,然后悲剧的事情来了。后台解析不了。查看了下数据 [8, 23, 18, 3, 97, 115, 100] 确实是传过去了。

后来排查出原因是应该是解析成了字符串,然后数值变了。所以解析不出来。 后来使用fromCharCode()方法编辑成字符串形式传输给后台。在使用charCodeAt()取值。

此方法已弃用
protobufferTest () {
   var message = new messages.Person() // 调用Person对象 实例化
   // 赋值
   message.setId(23)
   message.setName('asd')
   // 序列化
   var bytes = message.serializeBinary()

   console.log(bytes) // Uint8Array(7) [8, 23, 18, 3, 97, 115, 100]

   var tests = ''
   for (let index = 0; index < bytes.length; index++) {
    tests += String.fromCharCode(bytes[index])
   }
   console.log(tests) // asd

   // 存入FormData
   let uploadDatas = new FormData()
   uploadDatas.append('protobuf', tests)

   // 使用axios传输给后台
   this.axios.post('/test', uploadDatas)
    .then(function (response) {
     // 将传回的字符串转为数组
     console.log(response.data.split('')) // ["↵", "", "3", "2", "", "", "a", "s", "d", "f"]
     let str = response.data.split('')
     let toChar = []
     for (let index = 0; index < str.length; index++) {
      toChar.push(str[index].charCodeAt())
     }
     console.log(toChar) // [10, 2, 51, 50, 18, 4, 97, 115, 100, 102]

     // 后台传回来的是PersonTree里面的值所以调用PersonTree来反序列化
     var message2 = messages.PersonTree.deserializeBinary(toChar)

     console.log(message2) // proto.PersonTree {wrappers_: null, messageId_: undefined, arrayIndexOffset_: -1, array: Array(3), pivot_: 1.7976931348623157e+308, …}

     // 获取PersonTree的id值
     console.log(message2.getId()) // 32
    })
    .catch(function (error) {
     console.log(error)
    })

  }

以上方法可能存在安全隐患。 向后端传值 因为FormData支持两种方式传输string和blob所以将bytes存入blob中 前端获取数据 对axios的默认传输方式做个更改 axios.defaults.responseType = 'arraybuffer' 将以上的JS代码更改为以下内容

protobufferTest () {
   var message = new messages.Person()
   message.setId(23)
   message.setName('asd')
   var bytes = message.serializeBinary()
   
   console.log(bytes)
   let uploadDatas = new FormData()
   var blob = new Blob([bytes], {type: 'application/octet-stream'})

   uploadDatas.append('protobuf', blob)
   
   this.axios.post('/test', uploadDatas)
    .then(function (response) {
     console.log(response)

     var message2 = messages.PersonTree.deserializeBinary(response.data)
     console.log(message2.getId())
    })
    .catch(function (error) {
     console.log(error)
    })
   // console.log(bytes)
  }

至此前后联调完成

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

AngularJs IE Compatibility 兼容老版本IE

本文主要介绍AngularJs IE Compatibility 兼容老版本IE的问题及解决办法,有兴趣的小伙伴可以参考下
收藏 0 赞 0 分享

AngularJs Modules详解及示例代码

本文主要介绍AngularJs Modules的相关知识,这里整理了详细的资料及简单示例代码,有兴趣的朋友可以参考下
收藏 0 赞 0 分享

AngularJs Scope详解及示例代码

本文主要介绍AngularJs Scope的知识,这里整理了详细资料及示例代码,有兴趣的小伙伴可以参考下
收藏 0 赞 0 分享

node.js中module.exports与exports用法上的区别

Node.js 引入了模块(Module)概念,一个模块可以通过module.exports 或 exports 将函数、变量等导出,以使其它 JavaScript 脚本通过require() 函数引入并使用。那么node.js中module.exports与exports有什么
收藏 0 赞 0 分享

基于JS实现发送短信验证码后的倒计时功能(无视页面刷新,页面关闭不进行倒计时功能)

这篇文章主要介绍了基于JS实现发送短信验证码后的倒计时功能(无视页面刷新,页面关闭不进行倒计时功能)的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

基于jQuery实现发送短信验证码后的倒计时功能(无视页面关闭)

最近做了一个项目,其中有需求要求实现发送短信验证码后倒计时功能,其中有个难点:要求关闭页面也进行倒计时。好吧,下面小编把jquery 发送验证码倒计时的实现代码分享给大家,大家可以参考下
收藏 0 赞 0 分享

js绘制购物车抛物线动画

这篇文章主要为大家详细介绍了js绘制购物车抛物线动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

vue.js入门教程之绑定class和style样式

小编之前介绍了通过vue.js计算属性,不知道大家都学会了吗。那这篇文章中我们将一起学习vue.js实现绑定class和style样式,有需要的朋友们可以参考借鉴。
收藏 0 赞 0 分享

纯JS实现可拖拽表单的简单实例

下面小编就为大家带来一篇纯JS实现可拖拽表单的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

js实现StringBuffer的简单实例

下面小编就为大家带来一篇js实现StringBuffer的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多