基於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)); // 列印父模組此時資料【Firefox瀏覽器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