cocos2d-js中使用websocket

前端之家收集整理的这篇文章主要介绍了cocos2d-js中使用websocket前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面是一个简单的封装:
//Network.js
var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket;


var Network  = (function(){
	var instance = null;
	function getNetworkInstance (){
		var networkInstance = {
			socket:null,isInit:false,initNetwork:function(){
				cc.log('Network initSocket...');
				this.host = "ws://192.168.33.192:8080";
				this.testhost = "ws://echo.websocket.org"
				this.socket = new WebSocket(this.host);
				this.socket.onopen = function(evt){
					cc.log('Network onopen...');
					utils.outObj(evt);
					this.isInit = true;
				};
				
				this.socket.onmessage = function(evt){
					var data = evt.data;
					cc.log('Network onmessage...');
					utils.outObj(evt);
				};
				
				this.socket.onerror = function(evt){
					cc.log('Network onerror...');
					utils.outObj(evt);
				};
				
				this.socket.onclose = function(evt){
					cc.log('Network onclose...');
					utils.outObj(evt);
					this.isInit = false;
				};
			},send:function(data){
				if (this.isInit){
					cc.log('Network is not inited...');
				}else if(this.socket.readyState == WebSocket.OPEN){
					cc.log('Network send:'+data);
					this.socket.send(data);
				}else{
					cc.log('Network WebSocket readState:'+this.socket.readyState);
				}
			},close:function(){
				if (this.socket){
					cc.log("Network close...");
					this.socket.close();
					this.socket = null;
				}
			}
		};
		return networkInstance;
	};


	return {
		getInstance:function(){
			if(instance === null){
				instance = getNetworkInstance();
			}
			return instance;
		}
	};
})();

// 在main.js中加入
Network.getInstance().initNetwork();

// 在app.js中加入加入一个按钮,在按钮的点击事件中加入:
Network.getInstance().send("Hellow server");
原文链接:https://www.f2er.com/cocos2dx/343556.html

猜你在找的Cocos2d-x相关文章