Win7 + Creator 2.0.0 + protobufjs 6.8.8
1. Download and install Protobufjs
Install -G protobufjs
You can see that PROTOBUFJS is installed in C:\Users\Administrator\AppData\Roaming\npm\node_modules\protobufjs
2. Locate the Protobuf.js file in Protobufjs\dist and drag and drop it into the creator as a plugin (note that it must be selected as a plug-in, and four options must be checked, otherwise it will be an error!). )
3. Create a new communication protocol file Msg.proto, as follows:
" Proto3 " ;p ackage msg;message Login { string1; string pwd 2 ;}
Note: Package is a packet name msg
4. Use the following command to convert the Msg.proto file to the corresponding JS version file Msg.js
-T Static-module-W
5. Modify the contents of the Msg.js file
// var $protobuf = require ("Protobufjs/minimal");//Mask the line in the source file and add the following line var $protobuf = protobuf;
6. Drag and drop msg.js into creator (the structure containing the msg.js and protobuf.js files is as follows)
7. Write a websocket processing script to mount it in the scene.
Import {msg} from "./msg"//file is introduced herecc. Class ({extends:cc.Component, properties: {IP: {default: "", type:cc.string}, port: {default: 0, Type:cc.number}}, ctor:function () { This. WS =NULL; }, OnLoad:function () { varSelf = This; varIpport = "ws://" + This. IP + ":" + This. Port; Console.log (Ipport); This. WS =NewWebSocket (Ipport); This. Ws.binarytype = ' Arraybuffer ';//This is set to send binary data This. Ws.onopen =function(event) {Console.log ("Open"); //Open successfully send immediately if(Self.ws.readyState = = =websocket.open) {Let message= Msg. Login.create ({name: "Hello", pwd: "pwd"});//Constructing ObjectsLet Messagebuf = Msg. Login.encode (Message). Finish ();//to get binary data, be sure to use the Finish functionself.ws.send (MESSAGEBUF);//Send binary Data } }; 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"); }; }});
Reference transfer: "Simple use of protobuf in Cocoscreator"
Above.
Cocos Creator using Protobufjs