Cocos Creator 使用protobufjs

Win7 + Creator 2.0.0 + protobufjs 6.8.8node

1.下載安裝protobufjsnpm

npm install -g protobufjs

能夠看到protobufjs安裝在C:\Users\Administrator\AppData\Roaming\npm\node_modules\protobufjs中ide

 

2.在protobufjs\dist中找到protobuf.js文件,並做爲插件拖放到Creator中(注意,必須做爲插件,而且是四個選項都必須選中,不然將報錯!)函數

 

3.新建一個通信協議文件msg.proto,內容以下ui

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

注意:package爲包名msgthis

 

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

::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文件的結構以下)code

 

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的簡單使用

以上。

相關文章
相關標籤/搜索