- Home /
The question is answered, right answer was accepted
How do you add a timeout to the WWW class?
Question: How do you add a timeout to the WWW class?
Explanation: Currently I'm creating an account system where it connects to a server/file in php format. If the server is down, how would I go about creating an error?
Answer by fafase · Apr 18, 2014 at 10:15 AM
If the server is down, the request won't be successful so you will get an error.
WWW www = new WWW(url);
yield return www;
if(www.error != null)print (www.error);
You can also create your own time out:
WWW www = new WWW(url);
float timer = 0;
bool failed = false;
while(!www.isDone){
if(timer > timeOut){ failed = true; break; }
timer += Time.deltaTime;
yield return null;
}
if(failed)www.Dispose();
The above needs to be tested for confirmation that it works.
On line #10 you have to use: if (failed || www.error != null )
If not, if the server is down or internet is not available, www.isDone is set to true, then you exit from the "while" loop, thinking everything went ok, and that's not true.
Cheers
What about using this class?
public class TimeoutWWW : WWW {
private float timeout;
private float elapsedTime;
public TimeoutWWW(string url, float timeout) : base(url){
this.timeout = timeout;
this.elapsedTime = 0;
this.timedOut = false;
}
public override bool keepWaiting{
get{
if (elapsedTime > timeout){
timedOut = true;
return false;
}
elapsedTime += Time.deltaTime;
return base.keepWaiting;
}
}
public bool timedOut{ get; private set; }
}
Recommended way to use it is (so it's automatically disposed):
using (TimeoutWWW www = new TimeoutWWW(url)) {
yield return www;
if (www.timedOut) {
// Do something
}
else if (string.IsNullOrEmpty(www.error)) {
// Do something
}
else {
// Response received succefully
}
}
Answer by DavidHidvegi · Sep 07, 2017 at 10:09 AM
The Best Answer does not work on iOS and its not correct.
This will work:
IEnumerator DownloadFileWithTimeout(string URL)
{
WWW www = new WWW(URL);
float timer = 0;
float timeOut = 10;
bool failed = false;
while (!www.isDone)
{
if (timer > timeOut) { failed = true; break; }
timer += Time.deltaTime;
yield return null;
}
if (failed || !string.IsNullOrEmpty(www.error))
{
www.Dispose();
yield break;
}
}