creator使用protobuf
https://mp.weixin.qq.com/s/OIkcsJQfLSXnZoUfXZ61AQ

npm i protobufjs -g

pbts,用来将转化后的js文件转为ts

第一种静态使用方法

安装完成即可使用pbjs的命令编译:

pbjs -t static-module -w commonjs -o proto_pb.js *.proto
pbts -o proto_pb.d.ts proto_pb.js

1)下载protobufjs,最新版本为v6.8.8:
https://www.npmjs.com/package/protobufjs 或者 https://github.com/dcodeIO/protobuf.js
根据需要提取相关js,放入目标目录,导入为插件。

2)test.proto文件:

syntax = "proto3";
package tutorial;

message Person {
  string name = 1;
  int32 id = 2; // Unique ID number for this person.
  string email = 3;
}

message AddressBook {
  repeated Person people = 1;
}

3)编译:pbjs -t static-module -w commonjs -o proto_pb.js *.proto,把proto_pb.js文件考到项目中,改第一行

// var $protobuf = require("protobufjs/minimal");
var $protobuf = protobuf;

4)使用

let person = tutorial.Person.create({ name: "Tom", id: 18, email: "tom@email" });
let buffer = tutorial.Person.encode(person).finish();
let message = tutorial.Person.decode(buffer);
console.log(buffer);
console.log(message);

        // ws里面使用收到的二进制
        ws.onmessage = (event) => {
            var reader = new FileReader();
            reader.readAsArrayBuffer(event.data);
            reader.onload = (e) => {
                var buf = new Uint8Array(reader.result);
                this.rectMsg(buf);
            }
        };

5)更新.bat

echo "开始更新"
cd ../xxprotobuf
git pull
pbjs -t static-module -w commonjs -o ../xx/assets/scripts/proto/proto_pb.js ./protofiles/game/*.proto
echo "更新成功"
pause

6)新建protobufjs\minimal.js文件,内容为:
export default protobuf = protobuf;
给pb.js文件用,使这一行var $protobuf = require("protobufjs/minimal");不出错
7)拷贝文件

xcopy ..\xx\web-mobile\res\*.* .\web\m168\ /s /e /c /y /h /r
xcopy ..\xx\web-mobile\src\*.* .\web\m168\ /s /e /c /y /h /r

8)发布index.html,强制更新

        function GetRequest() {
            var url = location.search;
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        }
        Request = GetRequest();
        var t = parseInt(Request["t"]);
        if (t) {
            if ((t + 1000 * 10) < Date.now()) {
                window.location.href = './index.html?v=' + Date.now();
            }
        } else {
            window.location.href = './index.html?v=' + Date.now();
        }

        var gIdVal = Request["gid"];
        window['gIdVal'] = gIdVal;

标签: proto

添加新评论