溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

COCOS CREATOR(TS) 之HTTP通信

發(fā)布時間:2020-08-02 20:20:51 來源:網絡 閱讀:2284 作者:Aonaufly 欄目:開發(fā)技術

一 : XMLHttpRequest的封裝

export class HttpCell{
    private _xhr : XMLHttpRequest = null;
    private _server_url : string = null;
    private _callback : ( $isSucc : boolean , _http : HttpCell ,$data : any ) => void = null;
    private _timeout : number = null;
    private _formData : FormData = null;
    private _method : string = null;
    public constructor(){
        this._xhr = new XMLHttpRequest();
        this.listener2Handler( true );
    }

    public abortListener() : void{
        this.listener2Handler( false );
        this._server_url = null;
        this._callback = null;
    }

    public reset : Function = () : void => {
        this.listener2Handler( true );
    }

    private onComplete( $isSucc : boolean , $data : any , $target : HttpCell ) : void {
        if( this === $target ){
            this._callback( $isSucc , this , $data );
        }
    }

    private listener2Handler : Function = ( $isAdd : boolean ) : void => {
        if( $isAdd ){
            ListenerManager.getInstance().add( ListenerType.NetHttpComplete , this , this.onComplete.bind(this) );
            this._xhr.onload = ( ev: Event) : any => {
                if( this._xhr.status == 200 || this._xhr.status == 304 ){
                    let $res : any = 'response' in this._xhr ? this._xhr.response : this._xhr.responseText;
                    cc.warn(`[Http] error ${$res}`);
                }
            }
            if( this._timeout ){
                this._xhr.ontimeout = ( ev: ProgressEvent ) : any => {
                    cc.warn(`[Http] error timeout!`);
                }
            }
            this._xhr.onerror = (ev: ErrorEvent) : any => {
                cc.warn( `[Http] error ${ev.message}` );
            }
            this._xhr.onreadystatechange = () : void => {
                if (this._xhr.readyState == XMLHttpRequest.DONE && ( this._xhr.status >= 200 && this._xhr.status < 400) ) {
                    if( this._xhr.status == 200 ){
                        ListenerManager.getInstance().trigger( ListenerType.NetHttpComplete , true , this._xhr.response , this);
                    }else{
                        ListenerManager.getInstance().trigger( ListenerType.NetHttpComplete , false , this._xhr.status , this );
                    }
                    this._xhr.abort();
                }
            }
        }else{
            if( this._xhr.onload ) this._xhr.onload = null;
            if( this._xhr.ontimeout ) this._xhr.ontimeout = null;
            if( this._xhr.onerror ) this._xhr.onerror = null;
            if( this._xhr.onreadystatechange ) this._xhr.onreadystatechange = null;
            ListenerManager.getInstance().remove( ListenerType.NetHttpComplete  , this , this.onComplete.bind(this) );
        }
    }

    public send : Function = (
            $server_url : string ,
            $data : object ,
            $callback : ( $isSucc : boolean , _http : HttpCell ,$data : any ) => void,
            $dataFormat : TYPE_HTTP4DATAFORMAT = TYPE_HTTP4DATAFORMAT.___TEXT___ ,
            $isGet : boolean = true,
            $timeout : number = null
    ) : void => {
        this._server_url = $server_url;
        this._callback = $callback;
        this._timeout = $timeout;
        this._method = $isGet ? "GET" : "POST";
        if( $timeout ) this._xhr.timeout = $timeout;
        switch( $dataFormat ){
            case TYPE_HTTP4DATAFORMAT.___TEXT___: this._xhr.responseType = "text";break;
            case TYPE_HTTP4DATAFORMAT.___BINARY___ : this._xhr.responseType = "arraybuffer";break;
            case TYPE_HTTP4DATAFORMAT.___JSON___ : this._xhr.responseType = "json";break;
        }
        if( $data ){
            this._formData = new FormData();
            for( let $key of  Object.keys($data) ){
                this._formData.append( $key + `` , $data[$key] + `` );
            }
        }else{
            this._formData = null;
        }
        this.start();
    }

    private start : Function = () : void => {
        this._xhr.open( this._method , this._server_url , true );
        this._xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded"  );
        this._xhr.send( this._formData );
    }

    public tryAgain : Function = () : void => {
        this.start();
    }

    public destory() : void{
        this.abortListener();
        this._xhr = null;
    }
}

PS :
Ⅰ,onreadystatechange : 當HTTP請求狀態(tài)改變時觸發(fā)
①,status 狀態(tài)
②,response 得到后端返回的數據

Ⅱ,tryAgain : 當Http請求出現異常時 , 可以請求tryAgain重新請求一次

Ⅲ,send方法
①, 參數 $data = { name="123" , pwd="123456" }

二 : 數據類型

export enum TYPE_HTTP4DATAFORMAT{
    ___TEXT___ = 1,
    ___BINARY___ = 2,
    ___JSON___ = 3
}

三 : 封裝Http管理類

export class HttpNetManager{
    private static _instance : HttpNetManager = null;
    public static get Instance() : HttpNetManager{
        if( !HttpNetManager._instance )
            HttpNetManager._instance = new HttpNetManager();
        return HttpNetManager._instance;
    }

    private _list_cell : PoolObjects<IHttp_Data> = null;
    private _cur_loading : Map<HttpCell,IHttp_Data> = null;
    private readonly _try_count : number = 3;
    private readonly _try_wait_during : number = 350;
    private constructor(){
        this._list_cell = new PoolObjects(3);
        this._cur_loading = new Map();
    }

    public send : Function = (
        $server_url : string ,
        $data : object ,
        $callback : ( $isSucc : boolean ,$data : any ) => void,
        $dataFormat : TYPE_HTTP4DATAFORMAT = TYPE_HTTP4DATAFORMAT.___TEXT___ ,
        $isGet : boolean = true,
        $isTry : boolean = true,
        $timeout : number = null
    ) : void => {
        let $modle : IHttp_Data = this._list_cell.Free;
        let $cell : HttpCell = null;
        if( !$modle ){
            $cell = new HttpCell();
            $modle = {
                _http : $cell ,
                _isTry : $isTry ,
                _callback : $callback,
                _cur_index : 0
            };
            this._list_cell.addNew( $modle );
        }else{
            $cell = $modle._http;
            $modle._isTry = $isTry;
            $modle._callback = $callback;
            $modle._cur_index = 0;
            $cell.reset();
        }
        this._cur_loading.set( $cell , $modle );
        $cell.send(
            $server_url,
            $data,
            this.onHttpCallback.bind(this),
            $dataFormat,
            $isGet,
            $timeout
        );
    }

    private onHttpCallback : Function = ( $isSucc : boolean , _http : HttpCell ,$data : any  ) : void => {
        let $model : IHttp_Data = this._cur_loading.get( _http );
        const $complete : Function = () : void =>{
            $model._callback( $isSucc , $data );
            this._cur_loading.delete( _http );
            _http.abortListener();
            if( !this._list_cell.reInsert( $model ) ){
                _http.destory();
            }
        }
        if( !$isSucc ){
            if( $model._isTry && $model._cur_index <  this._try_count ){
                $model._cur_index ++;
                if( this._try_wait_during > 0 ){
                    setTimeout( () : void => {
                        _http.tryAgain();
                    } , this._try_wait_during );
                }else{
                    _http.tryAgain();
                }
            }else{
                $complete();
            }
        }else{
            $complete();
        }
    }
}

PS:
Ⅰ,_try_count參數 : 如果Http請求失敗 , 會再次請求幾次
Ⅱ,_try_wait_during: 等待多少毫秒后再次進行HTTP請求
Ⅲ,通過send發(fā)送Http請求 , 其參數$callback用來返回數據

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI