码迷,mamicode.com
首页 > Web开发 > 详细

cocos2d-js中使用websocket

时间:2015-04-08 13:09:32      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:websocket   cocos2d   

下面是一个简单的封装:
//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");


cocos2d-js中使用websocket

标签:websocket   cocos2d   

原文地址:http://blog.csdn.net/xufeng0991/article/details/44939149

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!