第一步:安装
npm install protobufjs-cli -g
npm install protobufjs --save
npm install reconnecting-websocket
第二步:创建message.proto文件
syntax = "proto3";
package Protocol;
message LoginToken {
string token = 1;
string cid = 2;
string uid = 3;
}
message MessageLink {
string token = 1;
string cid = 2;
string uid = 3;
}
第三步:生成对应的js以及ts文件
pbjs -t static-module -w es6 -o message.js message.proto
pbts -o message.d.ts message.js
第四步:引入
import { Protocol } from './message';
第五步:使用
const ws = new ReconnectingWebSocket(wsConfig.wsUrl, undefined, { debug: false, maxRetries: 10, maxReconnectionDelay: 3000, connectionTimeout: 5400 });
ws.onopen = () => {
// 赋值,编码
const loginProto = Protocol.LoginToken.create();
loginProto.cid = cid;
loginProto.token = token;
loginProto.uid = uid;
const bytes = Protocol.LoginToken.encode(loginProto).finish();
const loginBlob = new Blob([bytes]);
ws.send(loginBlob);
}
ws.onmessage = (e: any) => {
if (e.data && e.data instanceof Blob) {
const reader = new FileReader();
reader.readAsArrayBuffer(e.data);
reader.onload = (evt: any) => {
const bytes = evt.target.result;
// 解码
const messageProto = Protocol.MessageLink.decode(new Uint8Array(bytes));
}
}
}