84 lines
3.0 KiB
TypeScript
84 lines
3.0 KiB
TypeScript
import { StringToUint8Array, Uint8ArrayToString } from './CovertUtil';
|
|
import pbUtile ,{MsgGameStruct} from './protobufUtil'
|
|
|
|
export default class httpManager{
|
|
_name:string;
|
|
_url:string; //
|
|
_route:string;//url标签
|
|
_token:string;//
|
|
constructor(name:string){
|
|
this._name = name
|
|
this._token = ""
|
|
}
|
|
//配置服务器
|
|
setUrlPort(url:string,route:string){
|
|
this._url = url;
|
|
this._route = route
|
|
}
|
|
setTokenStr(token:string){
|
|
this._token = token
|
|
}
|
|
static getNormal(url:string,callback:Function)//普通获取http
|
|
{
|
|
let xhr = new XMLHttpRequest();
|
|
let urlSave = url
|
|
xhr.onreadystatechange = function () {
|
|
cc.log('xhr.readyState=' + xhr.readyState + ' xhr.status=' + xhr.status);
|
|
if (xhr.readyState === 4) {
|
|
if(xhr.status == 200)
|
|
{
|
|
let respone = xhr.responseText;
|
|
callback(respone);
|
|
}
|
|
else {
|
|
callback(undefined);
|
|
}
|
|
}
|
|
};
|
|
xhr.open('GET', url, true);
|
|
xhr.timeout = 8000;// 8 seconds for timeout
|
|
xhr.send();
|
|
}
|
|
//发送消息体到服务器
|
|
sendPostPbMessage(mainId:number,subId:number,pbBody:Uint8Array|null,callback){
|
|
let fullUrl = "http://"+this._url+this._route;
|
|
|
|
let ui8Package = pbUtile.SendMsgWithToken(this._token,mainId,subId,pbBody)
|
|
let xhr = new XMLHttpRequest();
|
|
let _this = this;
|
|
xhr.onreadystatechange = function () {
|
|
cc.log('xhr.readyState=' + xhr.readyState + ' xhr.status=' + xhr.status);
|
|
if (xhr.readyState === 4 && xhr.status == 200) {
|
|
let respone = xhr.responseText;
|
|
if(respone==null)
|
|
callback({mainId:-1,subId:0,msgBody:new Uint8Array()})
|
|
else
|
|
{
|
|
console.log("消息返回完成")
|
|
let tb = pbUtile.DeCodeBodyMsg(StringToUint8Array(respone))
|
|
if(tb.a==0)//消息体不匹配
|
|
callback({mainId:-1,subId:0,msgBody:new Uint8Array()})
|
|
else{
|
|
let opt = pbUtile.GetMsgHeadBody(tb.b)
|
|
callback(opt)
|
|
}
|
|
}
|
|
} else {
|
|
if (xhr.readyState === 4)
|
|
{
|
|
callback({mainId:-2,subId:0,msgBody:new Uint8Array()})
|
|
console.log("没有收到正常消息返回 readyState:"+xhr.readyState+" status:"+xhr.status)
|
|
}
|
|
}
|
|
};
|
|
xhr.withCredentials = false;
|
|
xhr.open('POST', fullUrl, true);
|
|
xhr.setRequestHeader("Content-Type", "application/x-protobuf");
|
|
|
|
xhr.timeout = 8000;// 8 seconds for timeout
|
|
console.log("post-msg:",fullUrl,mainId,subId)
|
|
xhr.send(Uint8ArrayToString(ui8Package));
|
|
}
|
|
|
|
|
|
} |