var WS = {
	init : function(){
		var me = this;
		
		if(me._pingTimer){
			clearTimeout(me._pingTimer);
		}
		me._pingTimer = setInterval(function(){
			me.ping();
		},30000);
		
		this.ws = new WebSocket("ws://"+ HOST +":3000/");
		this.ws.onopen = function(){
			//Web Socket 已连接上，使用 send() 方法发送数据
			me.ping();
		};
		this.ws.onmessage = function (evt){ 
			var received_msg = evt.data;
			if(received_msg.indexOf('EVENT') != -1){
				console.log("数据已接收...",received_msg);
				emitEventByJSON( JSON.parse(received_msg),false);
			}
			
		};
		this.ws.onclose = function(){ 
			// 关闭 websocket
			setTimeout(function(){
				me.init();
			},5000);
		};
	},
	ping : function(){
		this.ws && this.ws.send('ping');
	},
	sendToOther : function(jsonString){
		try{
			this.ws && this.ws.send('sendOther@_@'+ jsonString);
		}catch(e){}
	}
}

$(function(){
	WS.init();
})
