WebSocket中关于使用ProtoBuf传输数据介绍js部分

来源:互联网 发布:c 获取数据库实例名 编辑:程序博客网 时间:2024/06/04 20:15

前言介绍:

本案例主要介绍如何在js里把接收到的protobuf数据转换为对象与如何把对象转换为protobuf数据。
为了能简单说明问题,在本案例中只有js部分,关于后台服务的像前台发送数据部分在案例一中已经介绍。

环境需求:

需要github大神wiki提供的三个js文件:[本案例的下载中已经提供]
github:https://github.com/dcodeIO/ProtoBuf.js/wiki
1. ByteBufferAB.min.js
2. Long.min.js
3. ProtoBuf.min.js

代码介绍:

itstack.proto

//这里是一个proto文件,我们在www.itstack.org为想象,定义它下面分为大知识点模块,每个模块下又有子模块// 父模块message ParentModule{        // 序号        required int32 number = 1;        // 名称        required string name = 2;        // 子模块[repeated 可重复,相当于集合]        repeated ChildrenModule childrenModule= 3;}// 子模块message ChildrenModule{        // 序号        required int32 number = 1;        // 名称        required string name = 2;}

html文件

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><!-- 引入protobuf相关js文件 -->                                    <script src="lib/Long.min.js"></script>         <!-- https://raw.github.com/dcodeIO/Long.js/master/dist/Long.min.js --><script src="lib/ByteBufferAB.min.js"></script> <!-- https://raw.github.com/dcodeIO/ByteBuffer.js/master/dist/ByteBufferAB.min.js --><script src="lib/ProtoBuf.min.js"></script>     <!-- https://raw.github.com/dcodeIO/ProtoBuf.js/master/dist/ProtoBuf.min.js --><!-- ProtoBuf处理 --><script language="javascript" type="text/javascript">if (typeof dcodeIO === 'undefined' || !dcodeIO.ProtoBuf) {    throw(new Error("ProtoBuf.js is not present. Please see www/index.html for manual setup instructions."));}// 创建ProtoBufvar ProtoBuf = dcodeIO.ProtoBuf;// 先构造两个子模块// 子模块-1var ChildrenModule_1 = ProtoBuf.loadProtoFile("itstack.proto").build("ChildrenModule");var childrenModule_1 = new ChildrenModule_1();childrenModule_1.setNumber(1);childrenModule_1.setName("Nginx5.0 初级案例");// 子模块-2var ChildrenModule_2 = ProtoBuf.loadProtoFile("itstack.proto").build("ChildrenModule");var childrenModule_2 = new ChildrenModule_2();childrenModule_2.setNumber(2);childrenModule_2.setName("Nginx5.0 中级案例");// 父模块var ParentModule = ProtoBuf.loadProtoFile("itstack.proto").build("ParentModule");// 像父模块设置值var parentModule = new ParentModule();parentModule.setNumber(1);parentModule.setName("Nginx5.0");parentModule.setChildrenModule(new Array(childrenModule_1,childrenModule_2));// 打印父模块此时数据【火狐浏览器F12进行观察】console.log("ProtoBuf对象数据:");console.log(parentModule);// 模拟发送// 1.对象转字节:parentModule.toArrayBuffer()// 2.字节转对象:ParentModule.decode()var msgDec = ParentModule.decode(parentModule.toArrayBuffer());// 接收到的数据:console.info("接收到的数据:");console.info(parentModule.toArrayBuffer());// 打印转换后的信息console.info("经过ParentModule.decode转换后的数据:");console.info(msgDec);</script></head><body></body></html>

测试解图: