COCOS CREATOR(TS) 之HTTP通信

发布时间:2020-08-02 20:20:51 作者:Aonaufly
来源:网络 阅读:2283

一 : 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用来返回数据

推荐阅读:
  1. cocos creator http工具类(xmlRequest)
  2. 关于Cocos Creator脚本执行顺序的几点补充

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

cocos http ts

上一篇:用户组和权限管理

下一篇:MongoDB操作

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》