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");


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。