我用Unity(Mono)编写的游戏有一个奇怪的问题。我有登录功能,然后,在成功登录后,我发送了一些保持活动的请求,以确保令牌更新(我每隔30秒发送一次)。
问题是,经过一段时间(有时是1小时,有时是2.5小时),我的所有请求都有超时状态。
为了确保我的连接状态,我在代码中进行了一些检查:我正在向http://google.com和我的API的主网站(不是API调用。只是网站GET)进行简单的GET。当我下次在API上超时时我发现了:
实现:
一开始我一直在使用RestSharp
来处理请求,但问题出现了,并且决定抛弃RestSharp
,现在我们正在使用经典WebClient
class BetterWebClient : WebClient
{
private WebRequest _Request = null;
public TimeSpan? Timeout { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
this._Request = base.GetWebRequest(address);
if ( Timeout.HasValue )
{
_Request.Timeout = (int)Timeout.Value.TotalMilliseconds;
}
else
{
_Request.Timeout = 10*1000; //10s
}
if (this._Request is HttpWebRequest)
{
((HttpWebRequest)this._Request).AllowAutoRedirect = true;
}
return this._Request;
}
}
My HandleRequest功能(也称为Google和API网站)如下所示:
public static void HandleRequest<TR>(string url, RestResponse<TR> executeGetRequest) where TR : new()
{
using (BetterWebClient w = new BetterWebClient() {Timeout = TimeSpan.FromSeconds(2)})
{
try
{
string downloadString = w.DownloadString("http://www.google.com");
Debug.Log("Google request: OK");
}
catch ( Exception )
{
Debug.LogError("Google request failed");
}
try
{
string downloadString = w.DownloadString("myAPIwebsite");
Debug.Log("WorldOfRescue.com request: OK");
}
catch ( Exception )
{
Debug.LogError("WorldOfRescue.com request failed");
}
}
var client = new BetterWebClient() {Timeout = TimeSpan.FromSeconds(5)};
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json");
try
{
string downloadString = client.DownloadString(url);
Debug.Log("Request for "+url+ " completed. Response: " + downloadString);
}
catch ( WebException e )
{
Debug.Log(e.Status);
throw;
}
catch ( Exception e )
{
Debug.Log(e.ToString());
throw;
}
finally
{
client.Dispose();
}
}
你知道为什么会这样吗?看起来有些东西阻止我向特定网站发送请求,但同时其他网站工作正常。