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