欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

在cocos creator 中使用websocket

发布时间:2025/4/9 61 豆豆
生活随笔 收集整理的这篇文章主要介绍了 在cocos creator 中使用websocket 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

客户端

参考:https://allknowboy.com/posts/e8f856f4/

NetConfig.js

/*** 当前的网络配置*/ module.exports={host:"ws://localhost",port:3000};

NetControl.js

/*** Created by Administrator on 2018/4/17 0017.*/ //定义全局的变量 window.onfire=require("onfire"); //处理事件的类库 var netConfig=require('NetConfig'); var NetControl={_sock:{}, //当前的webSocket的对象connect: function () {if(this._sock.readyState!==1){//当前接口没有打开//重新连接this._sock = new WebSocket(netConfig.host+":"+netConfig.port);this._sock.onopen = this._onOpen.bind(this);this._sock.onclose = this._onClose.bind(this);this._sock.onmessage = this._onMessage.bind(this);}return this;},_onOpen:function(){onfire.fire("onopen");},_onClose:function(err){onfire.fire("onclose",err);},_onMessage:function(obj){onfire.fire("onmessage",obj);},send:function(msg){this._sock.send(msg);console.log("send msg"+msg);},};module.exports=NetControl;

onfire.js

/*** Created by Administrator on 2018/4/17 0017.*/ /**Copyright (c) 2016 hustcc http://www.atool.org/License: MIThttps://github.com/hustcc/onfire.js**/ /* jshint expr: true */ !function (root, factory) {if (typeof module === 'object' && module.exports)module.exports = factory();elseroot.onfire = factory(); }(typeof window !== 'undefined' ? window : this, function () {var __onfireEvents = {},__cnt = 0, // evnet counterstring_str = 'string',function_str = 'function',hasOwnKey = Function.call.bind(Object.hasOwnProperty),slice = Function.call.bind(Array.prototype.slice);function _bind(eventName, callback, is_one, context) {if (typeof eventName !== string_str || typeof callback !== function_str) {throw new Error('args: '+string_str+', '+function_str+'');}if (! hasOwnKey(__onfireEvents, eventName)) {__onfireEvents[eventName] = {};}__onfireEvents[eventName][++__cnt] = [callback, is_one, context];return [eventName, __cnt];}function _each(obj, callback) {for (var key in obj) {if (hasOwnKey(obj, key)) callback(key, obj[key]);}}/*** onfire.on( event, func, context ) -> Object* - event (String): The event name to subscribe / bind to* - func (Function): The function to call when a new event is published / triggered* Bind / subscribe the event name, and the callback function when event is triggered, will return an event Object**/function on(eventName, callback, context) {return _bind(eventName, callback, 0, context);}/*** onfire.one( event, func, context ) -> Object* - event (String): The event name to subscribe / bind to* - func (Function): The function to call when a new event is published / triggered* Bind / subscribe the event name, and the callback function when event is triggered only once(can be triggered for one time), will return an event Object**/function one(eventName, callback, context) {return _bind(eventName, callback, 1, context);}function _fire_func(eventName, args) {if (hasOwnKey(__onfireEvents, eventName)) {_each(__onfireEvents[eventName], function(key, item) {item[0].apply(item[2], args); // do the functionif (item[1]) delete __onfireEvents[eventName][key]; // when is one, delete it after triggle });}}/*** onfire.fire( event[, data1 [,data2] ... ] )* - event (String): The event name to publish* - data...: The data to pass to subscribers / callbacks* Async Publishes / fires the the event, passing the data to it's subscribers / callbacks**/function fire(eventName) {// fire eventsvar args = slice(arguments, 1);setTimeout(function () {_fire_func(eventName, args);});}/*** onfire.fireSync( event[, data1 [,data2] ... ] )* - event (String): The event name to publish* - data...: The data to pass to subscribers / callbacks* Sync Publishes / fires the the event, passing the data to it's subscribers / callbacks**/function fireSync(eventName) {_fire_func(eventName, slice(arguments, 1));}/*** onfire.un( event ) -> Boolean* - event (String / Object): The message to publish* When passed a event Object, removes a specific subscription.* When passed event name String, removes all subscriptions for that event name(hierarchy)** Unsubscribe / unbind an event or event object.** Examples** // Example 1 - unsubscribing with a event object* var event_object = onfire.on('my_event', myFunc);* onfire.un(event_object);** // Example 2 - unsubscribing with a event name string* onfire.un('my_event');**/function un(event) {var eventName, key, r = false, type = typeof event;if (type === string_str) {// cancel the event name if existif (hasOwnKey(__onfireEvents, event)) {delete __onfireEvents[event];return true;}return false;}else if (type === 'object') {eventName = event[0];key = event[1];if (hasOwnKey(__onfireEvents, eventName) && hasOwnKey(__onfireEvents[eventName], key)) {delete __onfireEvents[eventName][key];return true;}// can not find this event, return falsereturn false;}else if (type === function_str) {_each(__onfireEvents, function(key_1, item_1) {_each(item_1, function(key_2, item_2) {if (item_2[0] === event) {delete __onfireEvents[key_1][key_2];r = true;}});});return r;}return true;}/*** onfire.clear()* Clears all subscriptions**/function clear() {__onfireEvents = {};}return {on: on,one: one,un: un,fire: fire,fireSync: fireSync,clear: clear}; });

webSocket.js 

// Learn cc.Class: // - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html // - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html // Learn Attribute: // - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html cc.Class({extends: cc.Component,properties: {// foo: {// // ATTRIBUTES:// default: null, // The default value will be used only when the component attaching// // to a node for the first time// type: cc.SpriteFrame, // optional, default is typeof default// serializable: true, // optional, default is true// },// bar: {// get () {// return this._bar;// },// set (value) {// this._bar = value;// }// }, },// LIFE-CYCLE CALLBACKS: onLoad () {},onMessage:function(obj){console.log("It's HelloWorld onMessage----->"+obj);},onDestroy:function(){onfire.un(this.msssageFire);},button_click:function()//按钮事件 {var netControl=require('NetControl');console.log("开始连接");netControl.connect();console.log("连接完成");this.msssageFire=onfire.on("onmessage",this.onMessage.bind(this));var jsonTmp = "{ \"Mobile\": \"" + 121212 + "\", \"Password\": \"" + 121313454545 + "\" }";netControl.send("1010" + jsonTmp);console.log("sendToWS");},start () {},// update (dt) {}, });

 

nodejs服务器

参考网站

npm install websocket

在www文件中添加

var SocketServer = require('../game/socket-server'); SocketServer(server);

新建game文件夹socket-server.js

/*** Created by chu on 2017/8/16 0016.*/const SocketServer = function (server) {var WebSocket=require('ws');var io=new WebSocket.Server({server})io.on('connection',function(ws){console.log(`[SERVER] connection()`);ws.on('message', function (message) {console.log("接受消息");console.log(`[SERVER] Received: ${message}`);ws.send(`ECHO: ${message}`, (err) => {if (err) {console.log(`[SERVER] error: ${err}`);}});})})return io; }; module.exports = SocketServer;

 

转载于:https://www.cnblogs.com/zuhaoran/p/8862495.html

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的在cocos creator 中使用websocket的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。