Unity中Http的优化

xiaoxiao2021-02-28  106

前面讲过,在项目中经常会出现跨类传值,很多地方用到委托和事件,这样就比较分散,因此就出现了事件插件,用一个专门的对象管理项目中所有的事件


那么,同样在项目中很多地方,会有向服务器请求数据的需求,如果我们每个需求都单写一套,造成代码比较散乱,那么我们可以将项目中所有的http请求都交给一个对象来处理,这样代码比较简洁又利于后期维护

public class Http :MonoBehaviour{ private string _serverUrl = ""; private WWW _request; private ArrayList _cache = new ArrayList(); private bool _isRequesting = false; private int _errorTime = 0; /** * 初始化 */ public void Awake(){ } /** * Http错误处理函数 */ public void onError(){ if(this._errorTime > 10){ Log.errorTrace("连接异常"); return; } this._errorTime++; this.nextPost(); } /** * Http超时处理函数 */ public void onTimeOut(){ Log.errorTrace("您的请求已超时,请检查您的网络环境并重试"); } /** * 请求数据 * @param url 请求地址 * @param type 请求消息传递类型 * @param data 传递的参数 */ public void send(string url, EEvent type , WWWForm data = null , bool hasMask = false){ List<object> _dict = new List<object>(4); _dict.Add(url); _dict.Add(type); _dict.Add(data); _dict.Add(hasMask); this._cache.Add(_dict); this.post(); } /** * 请求服务器 */ public void post(){ if (this._isRequesting) { return; } if (this._cache.Count <= 0){ return; } List<object> arr = this._cache[this._cache.Count -1] as List<object>; string _url = (string)arr[0]; int _type = (int)arr[1]; WWWForm _data = (WWWForm)arr[2]; this._isRequesting = true; this._cache.RemoveAt(this._cache.Count - 1); StartCoroutine(postHttp(_url, _type, _data, (bool)arr[3])); } IEnumerator postHttp(string url, int type , WWWForm data = null , bool hasMask = false){ Log.trace(url); WWW www; if (data != null) { www = new WWW(url, data); yield return www; } else { www = new WWW(url); yield return www; } Debug.Log(www.text); if(www.error == null){ this._errorTime = 0; Dictionary<string,object> arr = null; if(www.text != null && www.text != ""){ //do what } this.nextPost(); } else { Log.errorTrace("Http错误代码:"+ www.error); this.nextPost(); } //Log.trace(transform.name); PoolCenter.GetInstance().clearObject("HttpPool", transform); } /** * 开始下一个请求 */ public void nextPost() { this._isRequesting = false; this.post(); } }

FR:海涛高软(QQ技术交流群:386476712)

转载请注明原文地址: https://www.6miu.com/read-60043.html

最新回复(0)