加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Cocos Creator 使用protobufjs

发布时间:2020-12-14 18:55:04 所属栏目:百科 来源:网络整理
导读:Win7 + Creator?2.0.0?+?protobufjs 6.8.8 1.下载安装protobufjs npm install -g protobufjs 可以看到protobufjs安装在C:UsersAdministratorAppDataRoamingnpmnode_modulesprotobufjs中 ? 2.在protobufjsdist中找到protobuf.js文件,并作为插件拖放

Win7 + Creator?2.0.0?+?protobufjs 6.8.8

1.下载安装protobufjs

npm install -g protobufjs

可以看到protobufjs安装在C:UsersAdministratorAppDataRoamingnpmnode_modulesprotobufjs中

?

2.在protobufjsdist中找到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的简单使用》

以上。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读