当前位置:Gxlcms > JavaScript > protobuf.js的下载与使用详解

protobuf.js的下载与使用详解

时间:2021-07-01 10:21:17 帮助过:91人阅读

因为ProtoBuf的序列化效率和大小都非常好,所以它在网络通信上面应用越来越多;而webosocket也随着web3.0应用越来越广泛,而将这两个结合在一起的也会慢慢形成一种趋势;本人是为了测试自已写的一个C# websocket,所以在web上面结合pb也写了一个js实例:

1.首先下载protobuf.js

2.引入protobuf相关js文件

<script src="/js/protobuf.js?1.1.11"></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             };            
 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);
 }27         function onClose(evt) {28             writeToScreen("DISCONNECTED");29         }30         function onMessage(evt) {31             var reader = new FileReader();32             reader.readAsArrayBuffer(evt.data);
 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.互通测试

以上就是protobuf.js的下载与使用详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行