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"  //这里引入文件
 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的简单使用

以上。

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...