[导读]因为ProtoBuf的序列化效率和大小都非常好,所以它在网络通信上面应用越来越多;而webosocket也随着web3.0应用越来越广泛,而将这两个结合在一起的也会慢慢形成一种趋势;
因为ProtoBuf的序列化效率和大小都非常好,所以它在网络通信上面应用越来越多;而webosocket也随着web3.0应用越来越广泛,而将这两个结合在一起的也会慢慢形成一种趋势;本人是为了测试自已写的一个C# websocket,所以在web上面结合pb也写了一个js实例:
1.首先下载protobuf.js
2.引入protobuf相关js文件
3.创建proto文件package wenlipackage;
syntax = "proto3";
message WSMessage {
required string id = 1;
required string content = 2;
required string sender = 3;
required string time = 4;
}
js的protobuf格式类型有
s-/u-/int32
s-/fixed32number (32 bit integer)value | 0 if signed
value >>> 0 if unsigned
s-/u-/int64
s-/fixed64Long-like (optimal)
number (53 bit integer)Long.fromValue(value) with long.js
parseInt(value, 10) otherwise
float
doublenumberNumber(value)boolbooleanBoolean(value)stringstringString(value)bytesUint8Array (optimal)
Buffer (optimal under node)
Array. (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 stringmessage
Valid messageMessage.fromObject(value)
4.初始化protobuf,对相关数据进行序列化和反序列化
1
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 WSMessage是一个解码编码器wsmessage是具体的某个定义的proto实例
是一个8位无符号的字节数组
5.连接到websocket并发送序列化的消息和接收反序列化的消息
var wsUri = "ws://127.0.0.1:8082/";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function (evt) {
onOpen(evt)
};
websocket.onclose = function (evt) {
onClose(evt)
};
websocket.onmessage = function (evt) {
onMessage(evt)
};
websocket.onerror = function (evt) {
onError(evt)
};
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend(buffer);
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
var reader = new FileReader();
reader.readAsArrayBuffer(evt.data);
reader.onload = function (e) {
var buf = new Uint8Array(reader.result);
writeToScreen('RESPONSE: ' + WSMessage.decode(buf).content + '');
}
}
function onError(evt) {
writeToScreen('ERROR: ' + evt.data);
}
function doSend(message) {
writeToScreen("SENT: " + wsmessage.content);
websocket.send(buffer);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
上面因为我的websocket server 返回一是二进制,所以浏览器接收到的是一个blob,这里注意对blob的处理
6.互通测试