protobuf 编译 java js文件详解

时间:2025-04-16 10:35:13

首先下载protobuf.exe

下载地址:https://download.****.net/download/qq_34756156/10220137

MessageBody.proto
syntax = "proto3";

message messagebody{
//工厂 3G
string factory = ; //设备id 3918173069
string deviceId = ; //内容长度的长度 消息类型+消息主体 = 内容长度
string length = ; //消息类型
string type = ; //消息主体
string body = ; //时间戳
string timeStamp = ; //发送人
string sender = ; //接收人
string receiver = ; //用户组编号
string groupId =;
}
 

编译解释:

工具编译 protoc.exe --java_out=编译的路径 源

java编译
F:\工具\portobuf>protoc.exe --java_out=F:\工具\portobuf\ SubscribeReq.proto js编译 F:\工具\portobuf>protoc.exe --js_out=import_style=commonjs,binary:. js\MessageBody.proto node.js编译 npm install -g require(对库文件的引用库)
npm install -g browserify(这个是用来打包成前端使用的js文件)
最后我们执行
npm install google-protobuf
会在当前目录下生成一个文件夹,里面装的就是protobuf的库文件。 都装好以后,只需要再写一个导出文件用browserify执行打包即可 var MessageBody = require('./MessageBody_pb'); module.exports = {
DataProto: MessageBody
} 保存为exports.js。 .对文件进行编译打包
执行命令
browserify exports.js > MessageBody.js
然后会生成一个MessageBody.js文件。 引入js使用
<script type="text/javascript" src="./MessageBody.js"></script>
socket = new WebSocket("ws://localhost:8111/websocket"); socket.binaryType = "arraybuffer";
if (event.data instanceof ArrayBuffer){
proto.messagebody.deserializeBinary(event.data); //如果后端发送的是二进制帧(protobuf)会收到前面定义的类型
} var content = new proto.messagebody();
content.setFactory("3G");//厂商
content.setDeviceid(deviceid);//设备id
content.setLength("");//长度
content.setType(message);//类型
content.setBody("0,150,56");//内容
var bytes = content.serializeBinary();