Cocos Creator 使用protobufjs

Cocos Creator 使用protobufjs,第1张

概述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.

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全部内容,希望文章能够帮你解决Cocos Creator 使用protobufjs所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/998946.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存