ProtoBuf.js – Protocol Buffers的Javascript實現

來源:互聯網
上載者:User

標籤:span   syn   發送   lis   tostring   lock   接受   讀取   under   

原文連結:ProtoBuf.js – Protocol Buffers的Javascript實現

推薦前端網址:http://keenwon.com/

在Javascript裡比較常見的資料格式就是json,xml,但是這兩種格式在資料轉送方面有明顯不足。而Protocol Buffers可以很好的解決這個問題,下面引用百科的對Protocol Buffers的定義:

 

Protocol Buffers是Google公司開發的一種資料描述語言 (Data Description Language),類似於XML能夠將結構化資料序列化,可用於資料存放區、通訊協定等方面。它不依賴於語言和平台並且可擴充性極強。現階段官方支援C++、JAVA、Python等三種程式設計語言,但可以找到大量的幾乎涵蓋所有語言的第三方拓展包。

 

同為資料的儲存格式,和json相比,Protocol Buffers的優點主要體現在效能和體積上,效能方面需要實際的測試,暫且不說,資料體積方面的優勢是比較明顯的,例如,一個json檔案:

 

  1. [
  2. {"Name": "zhangsan", "Gender": 0, "Age": 18},
  3. {"Name": "lisi", "Gender": 1, "Age": 19}
  4. ]

 

再看一個protobuf檔案:

 

  1. message Person {
  2. required string Name = 1;
  3. optional int32 Gender = 2;
  4. optional int32 Age = 3;
  5. }

 

json檔案的問題在於無效資料太多,例如Name 和Gender 等,這些內容大量重複出現,使得資料體積較大。再看protobuf檔案,它使用一個唯一的id(數字)來代替json裡複雜的key,這樣只要資料發送方和接受方都按同一套“模板”解析資料,就可以大大縮短報文體積。

 

ProtoBuf.js

ProtoBuf.js是基於ByteBuffer.js的Protocol Buffers純Javascript實現。主要功能是解析.proto 檔案,構建message類,和簡單的編碼、解碼。目前我在一個node-webkit中使用protobuf格式於服務端進行資料互動(服務端是按照舊c++用戶端要求實現的protobuf)。

 

 

目前對ProtoBuf.js的使用主要就是讀取舊的.proto 檔案,建立message類,編碼,發送給服務端,如下:

 

user.proto 檔案:

  1. package protobuf;
  2.  
  3. message UserModel {
  4. required string cyUserno = 1;
  5. required string cyPassWord = 2;
  6. required string cyStatus = 3;
  7. }

 

nodejs代碼:

  1. var fs = require("fs"),
  2. ProtoBuf = require("protobufjs"),
  3. userProtoStr = fs.readFileSync(‘./user.proto‘).toString(),
  4. UserModel = ProtoBuf.loadProto(userProtoStr).build(‘protobuf‘).UserModel,
  5. userModel;
  6.  
  7. userModel= new UserModel();
  8. userModel.set(‘cyUserno‘, ‘111111‘);
  9. userModel.set(‘cyPassWord‘, ‘123456‘);
  10. userModel.set(‘cyStatus‘, ‘1‘);
  11.  
  12. var buffer = userModel.encode().toBuffer();

 

解碼的方法也很簡單:

 

  1. var userInfo = UserModel.decode(data);
  2.  
  3. userInfo.get(‘cyUserno‘);
  4. ......

 

另外protobuf.js還提供了一些工具,例如.proto 和.json 的轉換等,具體參看他的官網:https://github.com/dcodeIO/ProtoBuf.js

 

- 完 -

ProtoBuf.js – Protocol Buffers的Javascript實現(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.