npm i -g protoc-gen-js
(建议全局安装)npm i -g browserify
npm i google-protobuf
文件名_pb.js
文件会在里面protoc --js_out=import_style=commonjs,binary:./lib ./*.proto
browserify .\lib\msg_pb.js -o ./lib/msg.js
proto文件
syntax = "proto3";
package Msg;
message TestMsg
{
int32 id = 1;
string str = 2;
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<title>proto</title>
<!-- 引入生成的js包文件 -->
<script src="msg.js"></script>
</head>
<body>
<!-- 引入生成的js包文件 -->
<script src="msg.js"></script>
<script>
var test = new proto.Msg.TestMsg();
test.setId(10);
test.setStr('hello world');
var u8array = test.serializeBinary();
var formData = new FormData();
formData.append('data', u8array);
const ws = new Websocket("")
// 二进制流转Msg
ws.onmessage = async function(e) {
var test = new proto.Msg.TestMsg.deserializeBinary(await e.data.arrayBuffer()).toObject()
console.log( test )
}
</script>
</body>
</html>
$$end have fun.