您的位置:首页 > Web前端 > JavaScript

基于Netty5.0高级案例二之WebSocket中关于使用ProtoBuf传输数据介绍js部分

2016-05-26 12:00 921 查看

基于Netty5.0高级案例二之WebSocket中关于使用ProtoBuf传输数据介绍js部分

前言介绍:

本案例主要介绍如何在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

//个人博客:www.itstack.org
//站长:付政委
//QQ:184172133

//这里是一个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;
}


www.itstack.org.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."));
}
// 创建ProtoBuf
var ProtoBuf = dcodeIO.ProtoBuf;

// 先构造两个子模块
// 子模块-1
var ChildrenModule_1 = ProtoBuf.loadProtoFile("itstack.proto").build("ChildrenModule");
var childrenModule_1 = new ChildrenModule_1();
childrenModule_1.setNumber(1);
childrenModule_1.setName("Nginx5.0 初级案例");

// 子模块-2
var 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>

测试解图:





工程下载:

http://itstack.qiniudn.com/TestJsProtobuf.zip

来自:http://www.itstack.org/?post=29
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: