var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket;

var WebSocketManager = cc.Class.extend({

    _wsObj:null,

    _wsReConnectTimes:,

    _reConnectMax:,

    _connectTimeout:,

    _reConnectFlag:false,

    _msg:null,

    _msgKey:null,

    _msgSendStatus:'nothing',

    _msgTimeout:,

    _msgTimeoutTimes:,

    _msgGet:'',

    _target:null,

    _callback:null,

    ctor:function () {

        NC.addObserver(this,this.connectTimeoutHandle,
'ws_connect_timeout');

        NC.addObserver(this,this.sendTimeoutHandle,
'ws_timeout');

    },

    //打开连接

    openConnect:function () {

       if(this._wsObj){

           this._wsObj.close();

           return;

        }

       this._wsObj =
null;

       var self =
this;

       this._wsObj =
new WebSocket(CFG_SER.ws_ser);

        cc.log("WS CONNECTING." + CFG_SER.ws_ser);

       //连接超时推断

        director.getScheduler().scheduleCallbackForTarget(,
, this._connectTimeout);

       this._wsObj.onopen =
function (evt) {

            self.openGet(evt);

        };

       this._wsObj.onmessage =
function (evt) {

            self.messageGet(evt);

        };

       this._wsObj.onerror =
function (evt) {

            self.errorGet(evt);

        };

       this._wsObj.onclose =
function (evt) {

            self.closeGet(evt);

        };

    },

    //连接超时推断

    connectTimeoutCheck:function(){

       if(CFG_SER.is_websock &&
this._wsObj && this._wsObj.readyState == WebSocket.CONNECTING){

           //重连次数

           if(this._wsReConnectTimes >this._reConnectMax){

                //重试过多后。应该提示玩家眼下网络不稳定

                GY_ti_shi_popup.getInstance().show(L('gy:ws_wang_luo_bu_wen'));

            }else{

               this._wsReConnectTimes++;

                GY_ti_shi_popup.getInstance().show(L('gy:ws_timeout'),'ws_connect_timeout');

            }

        }else{

           this.connectTimeoutHandle();

        }

    },

    //超时后又一次连接

    connectTimeoutHandle:function(){

       //又一次打开连接

       this.closeConnect();

    },

    //关闭连接

    closeConnect:function () {

        cc.log("WS CLOSING.");

       if(this._wsObj){

           this._wsObj.close();

        }

    },

    //连接后处理

    openGet:function (evt) {

        cc.log("WS was opened.");

        //获得连接的消息后,去掉超时推断

        director.getScheduler().unscheduleCallbackForTarget(this,this.connectTimeoutCheck);

       //清除重连次数

       this._wsReConnectTimes =
;

        //是否有未发送的消息又一次发送

       if (this._msgSendStatus =='msgReady' &&
this._msg) {

           this.sendRequest();

        }

    },

    //获得消息

    messageGet:function (evt) {

       this._msgGet = evt.data;

       try{

           )

                cc.log('response:' +this._msgGet);

           else

                cc.log('content too long to display.');

        }catch(e){

            cc.log('too large');

        }

       try{

           var resObj = JSON.parse(this._msgGet);

        }catch (e){

            GY_msg_popup.getInstance().show(L('gy:request_err'));

        }

       if (resObj._st ==
) {

            GY_tools.fan_yi_http_body(resObj._body);

           //推断是什么消息

           if(this._msgSendStatus =='msgSend' && resObj._body.func ==
this._msgKey){

               this.requestResponse(resObj);

            }else{

               switch (resObj._body.func){

                   case
'chong_zhi'://这里做一些自己的处理逻辑

                       break;

                }

            }

        }else{

            cc.log('request data err');

            GY_msg_popup.getInstance().show(L('gy:request_data_err'));

        }

    },

    //获取错误

    errorGet:function (evt) {

        cc.log("WS Error");

       this.closeConnect();

    },

    //连接关闭处理

    closeGet:function (evt) {

        cc.log("websocket instance closed.");

       this._wsObj =
null;

        //连接关闭立即进行重试

       this.openConnect();

    },

   /**

     * 给服务器发送消息

     * @param act

     * @param params

     * @param callback

     * @param target

     */

    sendGetRequest:function (act, params, callback, target) {

       this.beforeRequestSend(act, params, callback, target);

       //推断当前连接

       if (this.isOpen()) {

           this.sendRequest();

        }

       else {

           this.openConnect();

        }

    },

    //准备消息

    beforeRequestSend:function (act, params, callback, target) {

        //弹出loading

        GY_loading_popup.getInstance().show();

       //消息拼接

       this._msg = {'pathname':'',
'query':''};

       this._msg.pathname =
'/' + act;

        G.js_jiao_se ? params.id_jiao_se = G.js_jiao_se.id_jiao_se :null;

        //由于之前是HTTP的请求,须要将參数变成字符串的

       var p = {};

       for (key
in params) {

            p[key] ='' + params[key];

        }

       this._msg.query = p;

        //注冊消息,回调

       this._msgKey =
this._msg.pathname;

       this._target = target;

       this._callback = callback;

       this._msgSendStatus =
'msgReady';

    },

    //发送消息

    sendRequest:function () {

        cc.log('send request :');

        cc.log(JSON.stringify(this._msg));

       this._wsObj.send(JSON.stringify(this._msg));

       this._msgSendStatus =
'msgSend';

       //设置超时时间

        director.getScheduler().scheduleCallbackForTarget(,
, this._msgTimeout);

    },

    //消息被响应了

    requestResponse:function (resObj) {

        //获得响应的消息后,去掉loading遮罩

        director.getScheduler().unscheduleCallbackForTarget(this,this.sendTimeoutCheck);

       this._msg =
null;

       this._msgSendStatus =
'nothing';

        GY_loading_popup.getInstance().hide();

       this._callback.call(this._target, resObj._body);

    },

    //发送消息超时推断

    sendTimeoutCheck:function(){

       if(this._msgSendStatus =='msgSend'){

            //消息没有被响应。去掉loading遮罩

            GY_loading_popup.getInstance().hide();

            GY_ti_shi_popup.getInstance().show(L('gy:ws_timeout'),'ws_timeout');

        }

    },

    //超时后又一次获取玩家信息
并刷新当前页面

    sendTimeoutHandle:function(){

        var act ='gc/jiao_se/deng_lu';

       var param = {};

        param.gc_token = LS.getItem('gc_token');

        param.id_yong_hu = LS.getItem('id_yong_hu');

        param.zhouqi = LS.getItem('uc_zhouqi');

        HttpManager.create().sendGetRequest(act, param,this.callbackTimeoutHandle,
this);

    },

    //超时消息处理

    callbackTimeoutHandle:function(resObj){

       if (resObj.st_code ==
) {

           if (G.js_jiao_se.zt_jiao_se ==
) {

                SM.goto_page('DL_chuang_ming_page');

            }else
) {

                SM.goto_page('YD_yin_dao_' + G.js_jiao_se.xin_shou_jin_du +'_page');

            }else
) {

                //SM.goto_page('SY_shou_ye_page');

               //试试看直接刷新页面的效果吧

                SM.flush_page();

            }

        }

    },

    //推断ws是否已经连接

    isOpen:function(){

     return (this._wsObj &&this._wsObj.readyState == WebSocket.OPEN);

    },

    purge:function () {

        NC.removeObserver(this,'ws_timeout');

        NC.removeObserver(this,'ws_connect_timeout');

       this.closeConnect();

       this._instance =
null;

    }

});

WebSocketManager._instance =null;

WebSocketManager.getInstance =function () {

   if (!this._instance) {

       this._instance =
new WebSocketManager();

    }

   return
this._instance;

};

Cocos2d-x-javaScript 的webSocket的代码的更多相关文章

  1. Java 与 JavaScript 对websocket的使用

    ebsocket,HTML5中新一代全双工通信协议.其底层仍然是http协议. 传统 HTTP 请求响应客户端服务器交互图 WebSocket 请求响应客户端服务器交互图 WebSocket 客户端支 ...

  2. 如何实现 javascript “同步”调用 app 代码

    在 App 混合开发中,app 层向 js 层提供接口有两种方式,一种是同步接口,一种一异步接口(不清楚什么是同步的请看这里的讨论).为了保证 web 流畅,大部分时候,我们应该使用异步接口,但是某些 ...

  3. 在线运行Javascript,Jquery,HTML,CSS代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" http://www.w3.org/TR/xht ...

  4. 《Secrets of the JavaScript Ninja》:JavaScript 之运行时代码

    最近,在阅读 jQuery 之父 John Resig 力作:Secrets of the JavaScript Ninja(JavaScript忍者秘籍).关于第九章提及的 JavaScript 之 ...

  5. javascript 写一段代码,判断一个字符串中出现次数最多的字符串,并统计出现的次数

    javascript 写一段代码,判断一个字符串中出现次数最多的字符串,并统计出现的次数 function test(){ var bt = document.getElementById(" ...

  6. JavaScript创建读取cookie代码示例【附:跨域cookie解决办法】

    使用JavaScript 原生存取cookie代码示例: var cookie = { set : function(name, value, expires, path, domain, secur ...

  7. JavaScript之WebSocket技术详解

    概述 HTTP协议是一种无状态协议,服务器端本身不具有识别客户端的能力,必须借助外部机制,比如session和cookie,才能与特定客户端保持对话.这多多少少带来一些不便,尤其在服务器端与客户端需要 ...

  8. JavaScript调用App原生代码(iOS、Android)通用解决方案

    实际场景 场景:现在有一个H5活动页面,上面有一个登陆按钮,要求点击登陆按钮以后,唤出App内部的登录界面,当登录成功以后将用户的手机号返回给H5页面,显示出来.这个场景应该算是比较完整的一次H5中的 ...

  9. Javascript时间差计算函数代码实例

    Javascript时间差计算函数代码实例 <script language="javascript"> Date.prototype.dateDiff = funct ...

  10. javascript 元编程之-代码修改代码

    javascript 元编程之-代码修改代码 引言 重构代码是个体力活,特别是在确定重构方案后,剩下就是按方案调整代码,然后进行测试. 如何有好又快的调整到位代码,这是件不容易的事. 简单的代码,可以 ...

随机推荐

  1. [Usaco2007 Jan]Balanced Lineup排队

    [Usaco2007 Jan]Balanced Lineup排队 Time Limit: 5 Sec Memory Limit: 64 MB Submit: 2333 Solved: 1424 Des ...

  2. React 项目 ant design 的 CheckboxGroup 验证

    使用 ant design 提供的 getFieldDecorator 进行验证 一般开始使用默认选中 <FormItem> {getFieldDecorator('checkProtoc ...

  3. pycharm 安装激活

    下载pycharm :http://www.jetbrains.com/pycharm/download/download 安装 直到 finish 下载补丁jetbrains-agent.jar并添 ...

  4. android自定义camera以及uri和文件路径之间的转换

    相对直接调用系统的camera,这种方法使用得相对还少一些.根据api文档,步骤如下: 定义一个预览类 可以参照<android高薪之路>这本书上面,有这种方法的一种完整实现 而对应的ac ...

  5. CSS注

    1.css3内容上下左右居中 .box { display:-moz-box; -moz-box-pack:center; -moz-box-align:center; display:-webkit ...

  6. 《Effective Java》读书笔记 - 10.并发

    Chapter 10 Concurrency Item 66: Synchronize access to shared mutable data synchronized这个关键字不仅保证了同步,还 ...

  7. ES6中对字符串处理的优点

    目录 1.字符的Unicode表示法 2.字符串的遍历接口 3.直接输入 U+2028 和 U+2029(分行符 和 分段符) 4.JSON.stringify() 的改造 1.字符的Unicode表 ...

  8. 第五周学习总结&实验报告(三)

    第五周学习总结&实验报告(三) 这一周又学习了新的知识点--继承. 一.继承的基本概念是: *定义一个类,在接下来所定义的类里面如果定义的属性与第一个类里面所拥有的属性一样,那么我们在此就不需 ...

  9. Using FileUpload

    Using FileUpload FileUpload can be used in a number of different ways, depending upon the requiremen ...

  10. springboot+mybatis+SpringSecurity 实现用户角色数据库管理(一)

    本文使用springboot+mybatis+SpringSecurity 实现用户权限数据库管理 实现用户和角色用数据库存储,而资源(url)和权限的对应采用硬编码配置. 也就是角色可以访问的权限通 ...