COCOSCREATOR(TS)之HTTP通信-創(chuàng)新互聯(lián)

一 : 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 得到后端返回的數(shù)據(jù)

創(chuàng)新互聯(lián)從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術服務公司,擁有項目網(wǎng)站設計制作、成都網(wǎng)站設計網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元高陵做網(wǎng)站,已為上家服務,為高陵各地企業(yè)和個人服務,聯(lián)系電話:18982081108

Ⅱ,tryAgain : 當Http請求出現(xiàn)異常時 , 可以請求tryAgain重新請求一次

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

二 : 數(shù)據(jù)類型

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參數(shù) : 如果Http請求失敗 , 會再次請求幾次
Ⅱ,_try_wait_during: 等待多少毫秒后再次進行HTTP請求
Ⅲ,通過send發(fā)送Http請求 , 其參數(shù)$callback用來返回數(shù)據(jù)

另外有需要云服務器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。

名稱欄目:COCOSCREATOR(TS)之HTTP通信-創(chuàng)新互聯(lián)
文章起源:http://muchs.cn/article46/cdcohg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導航、網(wǎng)站排名、虛擬主機、做網(wǎng)站、手機網(wǎng)站建設、自適應網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

h5響應式網(wǎng)站建設