首先下載protobuf.exe
下載地址:https://download.csdn.net/download/qq_34756156/10220137
MessageBody.proto
syntax = "proto3"; message messagebody{ //工廠 3G string factory = 1; //設備id 3918173069 string deviceId = 2; //內容長度的長度 消息類型+消息主體 = 內容長度 string length = 3; //消息類型 string type = 4; //消息主體 string body = 5; //時間戳 string timeStamp = 6; //發送人 string sender = 7; //接收人 string receiver = 8; //用戶組編號 string groupId =9; }
編譯解釋:
工具編譯 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。 6.對文件進行編譯打包 執行命令 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("0009");//長度 content.setType(message);//類型 content.setBody("0,150,56");//內容 var bytes = content.serializeBinary();