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
原文地址:https://www.cnblogs.com/chevin/p/9515097.html