您的位置:首页 > 移动开发 > Cocos引擎

Cocos2d-x-javaScript 的webSocket的代码

2016-05-06 11:01 441 查看
原文

var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket;
var WebSocketManager = cc.Class.extend({

_wsObj:null,
_wsReConnectTimes:0,
_reConnectMax:3,
_connectTimeout:5,
_reConnectFlag:false,

_msg:null,
_msgKey:null,
_msgSendStatus:'nothing',
_msgTimeout:5,
_msgTimeoutTimes:0,

_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,this.connectTimeoutCheck,0, 0, 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 = 0;

//是否有未发送的消息重新发送
if (this._msgSendStatus =='msgReady' && this._msg) {
this.sendRequest();
}
},

//获得消息
messageGet:function (evt) {
this._msgGet = evt.data;
try{
if (this._msgGet.length <10000)
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 == 1) {
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,this.sendTimeoutCheck,0, 0, 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 == 1) {
if (G.js_jiao_se.zt_jiao_se == 1) {
SM.goto_page('DL_chuang_ming_page');
}else if (G.js_jiao_se.zt_jiao_se ==2) {
SM.goto_page('YD_yin_dao_' + G.js_jiao_se.xin_shou_jin_du +'_page');
}else if (G.js_jiao_se.zt_jiao_se ==3) {
//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;
};


代码版本久远,错误较多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息