1. 程式人生 > >javascript之ProtoBuf在websocket中的使用

javascript之ProtoBuf在websocket中的使用

java

因為ProtoBuf的序列化效率和大小都非常好,所以它在網絡通信上面應用越來越多;而webosocket也隨著web3.0應用越來越廣泛,而將這兩個結合在一起的也會慢慢形成一種趨勢;本人是為了測試自已寫的一個C# websocket,所以在web上面結合pb也寫了一個js實例:

1.首先下載protobuf.js

2.引入protobuf相關js文件

<script src="/js/protobuf.js"></script>

3.創建proto文件

技術分享

1 package wenlipackage;2 syntax = "proto3";3 4 message WSMessage {  
5     required string id = 1;6     required string content = 2;7     required string sender = 3;8     required string time = 4;9 }

技術分享

js的protobuf格式類型有

Field typeExpected JS type (create, encode)Conversion (fromObject)
s-/u-/int32
s-/fixed32
number (32 bit integer)value | 0 if signed
value >>> 0 if unsigned
s-/u-/int64
s-/fixed64
Long-like (optimal)
number (53 bit integer)
Long.fromValue(value) with long.js
parseInt(value, 10) otherwise
float
double
numberNumber(value)
boolbooleanBoolean(value)
stringstringString(value)
bytesUint8Array (optimal)
Buffer (optimal under node)
Array.<number> (8 bit integers)
base64.decode(value) if a string
Object with non-zero .length is assumed to be buffer-like
enumnumber (32 bit integer)Looks up the numeric id if a string
messageValid messageMessage.fromObject(value)

4.初始化protobuf,對相關數據進行序列化和反序列化

技術分享

 1 <script type="text/javascript">
 2         var WSMessage;
 3         var wsmessage;
 4         var buffer;
 5         protobuf.load("/proto/Message.proto", function (err, root) {
 6             if (err) throw err;
 7             WSMessage = root.lookup("wenlipackage.WSMessage");
 8             wsmessage = WSMessage.create({ id: "1", content: "hello", sender: "web", time: new Date().getTime() });
 9             buffer = WSMessage.encode(wsmessage).finish();
10         });
11 </script>

技術分享

WSMessage是一個解碼編碼器
wsmessage是具體的某個定義的proto實例
是一個8位無符號的字節數組

5.連接到websocket並發送序列化的消息和接收反序列化的消息

技術分享

 1 <script type="text/javascript"> 2         var wsUri = "ws://127.0.0.1:8082/"; 3         var output; 4         function init() { 5             output = document.getElementById("output"); 6             testWebSocket(); 7         } 8         function testWebSocket() { 9             websocket = new WebSocket(wsUri);10             websocket.onopen = function (evt) {11                 onOpen(evt)12             };13             websocket.onclose = function (evt) {14                 onClose(evt)15             };16             websocket.onmessage = function (evt) {17                 onMessage(evt)18             };19             websocket.onerror = function (evt) {20                 onError(evt)21             };22         }23         function onOpen(evt) {24             writeToScreen("CONNECTED");25             doSend(buffer);26         }27         function onClose(evt) {28             writeToScreen("DISCONNECTED");29         }30         function onMessage(evt) {31             var reader = new FileReader();32             reader.readAsArrayBuffer(evt.data);33             reader.onload = function (e) {34                 var buf = new Uint8Array(reader.result);35                 writeToScreen(‘<span style="color: blue;">RESPONSE: ‘ + WSMessage.decode(buf).content + ‘</span>‘);36             }37         }38         function onError(evt) {39             writeToScreen(‘<span style="color: red;">ERROR:</span> ‘ + evt.data);40         }41         function doSend(message) {42             writeToScreen("SENT: " + wsmessage.content);43             websocket.send(buffer);44         }45         function writeToScreen(message) {46             var pre = document.createElement("p");47             pre.style.wordWrap = "break-word";48             pre.innerHTML = message;49             output.appendChild(pre);50         }51         window.addEventListener("load", init, false);52 </script>

技術分享

上面因為我的websocket server 返回一是二進制,所以瀏覽器接收到的是一個blob,這裏註意對blob的處理

技術分享

6.互通測試

技術分享


javascript之ProtoBuf在websocket中的使用