COCOS CREATOR(TS) 之HTTP通信

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

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

时间: 2024-08-02 00:33:28

COCOS CREATOR(TS) 之HTTP通信的相关文章

COCOS CREATOR(TS)之setTimeOut

一 : 前景 有很多前端可能觉得setTimeOut不值得一讲,But,在不同的平台setTimeOut的执行是有一定的规则需要遵守,有时也叫迫于无奈.比如,前几日的开发中发现一个非常奇怪的现象 , 就是setOutTime在Web / 微信IDE端都是可以起作用的 , 但是一旦到了手机微信中运行,好似就不那么灵光了.今日抽了点时间好好测试了一番 , 内容如下: 二 : 测试 Ⅰ,测试环境如下(使用TS代码)Ⅱ,代码1,测试思想分别给出有参数(setTimeOut自带传参和setTimeOut不

COCOS CREATOR(TS)之节点鼠标事件

一 : 前景 以官方的Demo为例子(HelloWorld)①-> UI层级结构②-> Canvas的属性 二 : 编码(Helloworld.ts) const {ccclass, property} = cc._decorator; @ccclass export default class Helloworld extends cc.Component { @property(cc.Label) label: cc.Label = null; @property text: string

COCOS CREATOR(TS)之按钮事件

一 : 前景介绍 为cc.Button添加事件的方法有很多种 , 本篇只讲解使用cc.Component.EventHandler的方法.因为此方案有一个最大的有点 : 可以获得cc.Event.EventTouch.但是此方案,相比如控件拖动方案要复杂一些,所以给出此Blog予以详解 二 : 详解 Ⅰ: 构建cc.Component.EventHandler对象 export class ClickEvent2CreatTool{ private static _instance : Clic

COCOS CREATOR(TS)之SrollBar的基本修改

一 : 前言 初始化的ScrollBar如下:看到这个的时候 , 我有几点一下感悟 :① -> 我觉得scrollBar(滚动条)很丑 , 而且我不需要滚动条② -> 我我的背景不错 , but我还是希望是透明的 , 以看到底层的棕色背景这就是需要修改原(官方)ScrollBar的地方,之所以作出如上的修改需求,是因为在Game中,大部分这样的界面,都不需要滚动条和背景 . 当然特殊的除外(比如聊天,可能需要一个) 二 : 修改 Ⅰ ,移除滚动条① -> 选择ScrollView节点(N

Cocos Creator 脚本模板

1.由于新建Cocos Creator脚本带有很多注释,并且有时候需要增加定制的默认注释,所以需要修改脚本生成模板. 2.在CocosCreator\resources\static\template目录下,找到new-script.js/new-script.ts并进行修改.

cocos creator学习01 关于cocos creator 通过get 和post连接node.js服务器的初步探索

一.node.js的安装注意事项 1.参考http://www.runoob.com/nodejs/nodejs-install-setup.html 2.node.js如果不配置package.json文件会出现警告  npm WARN saveError ENOENT : no such file or directory ......输入 npm init 进行配置该文件 3.如果npm文件丢失,在控制面板->程序 选择修复. 4.出现express错误,需要在运行的工程的文件夹里进行ex

在 Cocos Creator 中使用 Protobufjs(一)

一. 环境准备 我一直在探索Cocos H5正确的开发姿势,目前做javascript项目已经离不开 nodejs.npm或grunt等脚手架工具了. 1.初始化package.json文件 npm init 当新建好cocos-js或creator项目,在项目根目录使用npm init命令,一路回车,将在当前目录创建package.json文件用于nodejs三方模块的管理.关于npm的使用细节网络上有很多教程,在此不用细说. 2. protobufjs模块 本人最早在cocos2dx 2.x

cocos creator主程入门教程(一)—— 初识creator

四邑隐侠,本名关健昌,10年游戏生涯,现隐居四邑.本系列文章以TypeScript为介绍语言. 我们在cocos creator新建一个Hello TypeScript项目,都会有一个assets/Scene/helloworld.fire文件.使用cocos creator开发游戏时,项目可以只有一个.fire文件.一般地,我会把这个文件夹改名为assets/scene,下面只有main.fire文件:assets/scene/main.fire. 双击main.fire文件,在层级管理器可以

cocos Creator js 房卡麻将/血战/H5四川麻将源码下载搭建

房卡麻将/血战/H5四川麻将 源码 支持iOS/Android/H5 完整源码 1.基于NODEJS+MYSQL的服务器,成熟的技术方案,高效稳定,且方便Windows开发,Linux平台布署,节约服务器运转成本. 2.采用最新版本的cocos引擎,cocos creator开发,可快速的进行界面调整.且能够快速地发布iOS,Android版本. 3.如需H5版本,只需针对H5平台进行资源优化即可. 4.成熟可靠的房卡式设计,能满足大部分用户使用体验. 5.产品经过大量测试,可以运转稳定. 测试