码迷,mamicode.com
首页 > Web开发 > 详细

COCOS CREATOR(TS) 之HTTP通信

时间:2019-01-26 17:53:57      阅读:1103      评论:0      收藏:0      [点我收藏+]

标签:exp   export   The   targe   cts   target   tar   name   open   

一 : 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请求状态改变时触发
①,status 状态
②,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发送Http请求 , 其参数$callback用来返回数据

COCOS CREATOR(TS) 之HTTP通信

标签:exp   export   The   targe   cts   target   tar   name   open   

原文地址:http://blog.51cto.com/aonaufly/2346900

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!