出现一个很难复现的错误,但概率较高, 1.5.1 没出现过, 1.6.0 之后都有。 底层打出错误日志:
Response failed, error buffer: The network connection was lost.
之后 HttpRequest 就发不出 http 请求了, 总是报 timeout.
代码如下:
var xhr = cc.loader.getXMLHttpRequest();
xhr.cb = cb;
xhr.ontimeout = function(){
xhr.isAborted = true;
xhr.abort();
if (xhr.cb){
console.log("ontimeout");
xhr.cb(-1, "ontimeout;" + url);
xhr.cb = null;
}
};
xhr.timeout = 15000;
xhr.onreadystatechange = function () {
if (!xhr || xhr.isAborted){
console.log("abourted");
return;
}
if (xhr.readyState == 4) {
var response = xhr.responseText;
if (xhr.cb){
var resp = {};
if(xhr.status == 200){
resp = JSON.parse(response);
if (resp.errorCode == ERROR_TOKEN_EXPIRED){
// 这里是我们的特殊退出处理, 防止多端登录。
tryQuit(true);
}
else{
xhr.cb(null, resp);
}
}
else{
//
xhr.cb(xhr.status || -1, "on_" + xhr.status + ";" + url);
}
xhr.cb = null;
}
}
};
xhr.onerror = function(){
if (xhr.cb){
console.log("onerror");
xhr.cb(-2, "onerror;" + url);
xhr.cb = null;
}
};
params = params || {};
var strParam = "";
for(var key in params) {
if (strParam.length > 0){
strParam = strParam + "&";
}
strParam = strParam + String.format("{0}={1}", key, params[key]);
}
if (cc.sys.isNative) {
if("win32" != dy.utils.platform()){
xhr.setRequestHeader("Accept-Encoding","gzip,deflate");
}
}
method = method || "GET";
if(method == "GET"){
if (strParam.length > 0){
url = encodeURI(String.format("{0}?{1}&{2}={3}", url, strParam, "ts"+dy.utils.currentTick(), dy.utils.currentTick()));
}
xhr.open('GET', url, true);
xhr.send();
}
else{
xhr.open('POST', url, true);
strParam = encodeURI(strParam);
xhr.send(strParam);
}
