using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
namespace Engine.Http
{
/// 接受消息委托
public delegate bool HandleHttpMessage(HttpResponse httpResponse);
/// http控制器
internal class HttpManager
{
#region 单利
private static HttpManager _Instance;
/// 单利函数
public static HttpManager GetInstance()
{
if (_Instance == null)
{
_Instance = new HttpManager();
}
return _Instance;
}
#endregion
public const float ResponseOverTimeLimit = 80000;
/// 接受到消息事件
private HandleHttpMessage onHandleHttpMessage = null;
/// 请求列表
private List mMsgList = new List();
/// 是否有消息正在请求中,优化Update函数
private bool IsMsgRquestIng = false;
/// 添加接受消息事件
public void AddHttpMessageEvent(HandleHttpMessage handleHttpMessage)
{
onHandleHttpMessage += handleHttpMessage;
}
/// 删除接受消息事件
public void DelHttMessageEvent(HandleHttpMessage handleHttpMessage)
{
onHandleHttpMessage -= handleHttpMessage;
}
/// 发送消息
public void SendMessage(HttpRequest httpRequest, Action callback = null)
{
//获得消息对象
HttpMsg httpMsg = OnGetHttpMsg();
//发送请求
httpMsg.SendMsg(httpRequest, callback);
//修改等待标记
IsMsgRquestIng = true;
}
/// 得到一个HttpMsg对象
private HttpMsg OnGetHttpMsg()
{
HttpMsg httpMsg = null;
int msgCount = mMsgList.Count;
for (int i = 0; i < msgCount; i++)
{
if (!mMsgList[i].IsUseIng)
{
httpMsg = mMsgList[i];
break;
}
}
if (httpMsg==null)
{
httpMsg = new HttpMsg();
mMsgList.Add(httpMsg);
}
return httpMsg;
}
/// 帧频函数
public void OnUpdate(int nTime)
{
//不存在消息处理逻辑,跳出,缓存全部的已经收到消息
if (!IsMsgRquestIng)
{
return;
}
int msgCount = mMsgList.Count;
for (int i = 0; i < msgCount; i++)
{
if (mMsgList[i].IsUseIng)
{
mMsgList[i].OnUpdate(nTime);
}
}
}
/// 帧频函数
public void OnFixedUpdate(int nTime)
{
//不存在消息处理逻辑,跳出,缓存全部的已经收到消息
if (onHandleHttpMessage == null || !IsMsgRquestIng)
{
return;
}
bool isRequestIng = false;
int msgCount = mMsgList.Count;
for (int i = 0; i < msgCount; i++)
{
//没用使用中直接跳过
if (!mMsgList[i].IsUseIng)
{ continue; }
//执行完成逻辑
if (mMsgList[i].IsRequestComplete)
{
//执行回调
onHandleHttpMessage(mMsgList[i].mHttpResponse);
mMsgList[i].SendCallBack();
//释放消息对象
mMsgList[i].Reset();
//修改等待标记
isRequestIng = true;
}
//修改等待标记
else
{
if(mMsgList[i].IsTimeout)
mMsgList[i].Reset();
isRequestIng = true;
}
}
//修改消息检查标记
IsMsgRquestIng = isRequestIng;
}
}
}