1. 程式人生 > >Cocos Creator 使用protobufjs

Cocos Creator 使用protobufjs

-o ack eat 協議 ssa stat 9.png 二進制 users

Win7 + Creator 2.0.0 + protobufjs 6.8.8

1.下載安裝protobufjs

npm install -g protobufjs

技術分享圖片

可以看到protobufjs安裝在C:\Users\Administrator\AppData\Roaming\npm\node_modules\protobufjs中

2.在protobufjs\dist中找到protobuf.js文件,並作為插件拖放到Creator中(註意,必須作為插件,並且是四個選項都必須選中,否則將報錯!)

技術分享圖片

3.新建一個通訊協議文件msg.proto,內容如下

syntax = "
proto3"; package msg; message Login { string name = 1; string pwd = 2; }

註意:package為包名msg

4.使用如下命令將msg.proto文件轉為對應的js版本文件Msg.js

::protobuf.js版本6.x生成js文件
pbjs -t static-module -w commonjs -o Msg.js msg.proto 

5.修改Msg.js文件對應內容

//var $protobuf = require("protobufjs/minimal"); //將源文件中的這一行屏蔽,然後新增下面一行
var $protobuf = protobuf;

6.將Msg.js拖放到Creator中(包含Msg.js和protobuf.js文件的結構如下)

技術分享圖片

7.寫一個WebSocket的處理腳本掛載到場景中即可。

import {msg} from "./Msg"  //這裏引入文件

cc.Class({
    extends: cc.Component,

    properties: {
        ip: {
            default: "",
            type: cc.string
        },

        port: {
            
default: 0, type: cc.number } }, ctor: function () { this.ws = null; }, onLoad: function () { var self = this; var ipPort = "ws://" + this.ip + ":" + this.port; console.log(ipPort); this.ws = new WebSocket(ipPort); this.ws.binaryType = ‘arraybuffer‘; //這裏設置為發送二進制數據 this.ws.onopen = function (event) { console.log("open"); //打開成功立刻進行發送 if (self.ws.readyState === WebSocket.OPEN) { let message = msg.Login.create({name: "hello", pwd: "pwd"});//構造對象 let messageBuf = msg.Login.encode(message).finish(); //獲取二進制數據,一定要註意使用finish函數 self.ws.send(messageBuf); //發送二進制數據 } }; this.ws.onmessage = function (event) { console.log("onmessage : " + event.data); }; this.ws.onerror = function (event) { console.log("on error :", event.data); }; this.ws.onclose = function (event) { console.log("onclose"); }; } });

參考傳送:《cocosCreator中Protobuf的簡單使用》

以上。

Cocos Creator 使用protobufjs