详解vue中使用protobuf踩坑记


Posted in Javascript onMay 07, 2019

官方解释为:

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)
  }

至此前后联调完成

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

Javascript 相关文章推荐
让广告代码不再影响你的网页加载速度
Jul 07 Javascript
ExtJs的Date格式字符代码
Dec 30 Javascript
javascript的事件触发器介绍的实现
Jun 05 Javascript
简述AngularJS相关的一些编程思想
Jun 23 Javascript
JS实现黑色大气的二级导航菜单效果
Sep 18 Javascript
jQuery Validation Plugin验证插件手动验证
Jan 26 Javascript
Javascript动画效果(1)
Oct 11 Javascript
B/S(Web)实时通讯解决方案分享
Apr 06 Javascript
JQuery实现定时刷新功能代码
May 09 jQuery
JavaScript学习笔记之图片库案例分析
Jan 08 Javascript
Vue中keep-alive组件作用详解
Feb 04 Javascript
vue自定义组件实现双向绑定
Jan 13 Vue.js
Node.js一行代码实现静态文件服务器的方法步骤
May 07 #Javascript
微信小程序扫描二维码获取信息实例详解
May 07 #Javascript
Vue数据绑定简析小结
May 07 #Javascript
javascript实现对话框功能警告(alert 消息对话框)确认(confirm 消息对话框)
May 07 #Javascript
详解Vue、element-ui、axios实现省市区三级联动
May 07 #Javascript
webpack结合express实现自动刷新的方法
May 07 #Javascript
记录一次开发微信网页分享的步骤
May 07 #Javascript
You might like
The specified CGI application misbehaved by not returning a complete set of HTTP headers
2011/03/31 PHP
一个显示某段时间内每个月的方法 返回由这些月份组成的数组
2012/05/16 PHP
简单的php数据库操作类代码(增,删,改,查)
2013/04/08 PHP
从PHP $_SERVER相关参数判断是否支持Rewrite模块
2013/09/26 PHP
PHP的Socket网络编程入门指引
2015/08/11 PHP
php 二维数组时间排序实现代码
2016/11/19 PHP
PHP 计算两个特别大的整数实例代码
2018/05/07 PHP
PHP配合fiddler抓包抓取微信指数小程序数据的实现方法分析
2020/01/02 PHP
表单的一些基本用法与技巧
2006/07/15 Javascript
childNodes.length与children.length的区别
2009/05/14 Javascript
Extjs4 Treegrid 使用心得分享(经验篇)
2013/07/01 Javascript
认识Knockout及如何使用Knockout绑定上下文
2015/12/25 Javascript
vue.js表格组件开发的实例详解
2016/10/12 Javascript
node+express制作爬虫教程
2016/11/11 Javascript
jQuery插件HighCharts实现的2D条状图效果示例【附demo源码下载】
2017/03/15 Javascript
canvas绘制一个常用的emoji表情
2017/03/30 Javascript
javaScript强制保留两位小数的输入数校验和小数保留问题
2018/05/09 Javascript
详解webpack之图片引入-增强的file-loader:url-loader
2018/10/08 Javascript
Vue 页面权限控制和登陆验证功能的实例代码
2019/06/20 Javascript
ECharts地图绘制和钻取简易接口详解
2019/07/12 Javascript
[06:16]第十四期-国士无双绝地翻盘之撼地神牛
2014/06/24 DOTA
Python学习笔记整理3之输入输出、python eval函数
2015/12/14 Python
Python中对象的引用与复制代码示例
2017/12/04 Python
对python程序内存泄漏调试的记录
2018/06/11 Python
Python values()与itervalues()的用法详解
2019/11/27 Python
python GUI库图形界面开发之PyQt5工具栏控件QToolBar的详细使用方法与实例
2020/02/28 Python
详解PyQt5中textBrowser显示print语句输出的简单方法
2020/08/07 Python
NBA欧洲商店(英国):NBA Europe Store UK
2018/07/27 全球购物
SAZAC的动物连体衣和动物睡衣:Kigurumi Shop
2020/03/14 全球购物
专业求职信撰写要诀
2014/02/18 职场文书
委托书的格式
2014/08/01 职场文书
党支部活动策划方案
2014/08/18 职场文书
财务助理岗位职责范本
2014/10/09 职场文书
小学班主任个人总结
2015/03/03 职场文书
国王的演讲观后感
2015/06/03 职场文书
mysql多表查询-笔记七
2021/04/05 MySQL