Cocos Creator 使用protobufjs


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"  //這里引入文件,msg為package的包名
 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"); }; } });

 

PS:在實際應用中,可能需要在二進制數據前再拼接一些數據才進行發送

8.在二進制數據前再拼接一個short數據

              let message = msg.Login.create({name: "hello", pwd: "pwd"}); let msgEncode = msg.Login.encode(message).finish(); //一定要注意使用finish函數

                //二進制數據的長度+一個short的長度
                var sendBuf = new ArrayBuffer(msgEncode.length + 2); var dv = new DataView(sendBuf); dv.setInt16(0,1); //寫入一個short值

                //將二進制數據寫入
                var u8view = new Uint8Array(sendBuf, 2); //跳過一個short的距離
                for (var i = 0, strLen = msgEncode.length; i < strLen; ++i){ u8view[i] = msgEncode[i]; } self.ws.send(sendBuf);

 

9.使用JAVA的WebSocketServer接口,很方便就可以接收並處理數據

 @Override public void onMessage(WebSocket conn, ByteBuffer message) { try { short val = message.getShort(); //獲取short值
            Msg.Login login = Msg.Login.parseFrom(message); Log.info("val = %d name : %s pwd : %s", val, login.getName(), login.getPwd()); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } }

輸出結果

 

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

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM