Question by
Wylie-Modro · Jan 07, 2017 at 02:59 AM ·
networkcoroutineyieldcoroutinesinternet
Checking Internet inside a Coroutine
I am attempting to check the internet connection at multiple points during the actual gameplay without bombing the fps of the game. I thought I could achieve this through coroutines but at the moment when I call StartCoroutine(CheckInternetCoroutine())
it seems to run the entire CheckInternet()
in one frame causing the game to lag a full second or more even with a fast internet connection.
Am I using the Coroutine incorrectly? Or can CheckInternet()
simply not be broken down into a Coroutine in the manner in which I have presented, if so how do can I do that?
StartCoroutine(CheckInternetCoroutine())
is called after a certain gameobject has been instantiated.
IEnumerator CheckInternetCoroutine(GameObject CloneObject, Vector3 loadedSpawnPos) {
internetChecker.CheckInternet ();
CloneObject.transform.position = loadedSpawnPos;
yield return null;
}
Then within the class InternetChecker:
public void CheckInternet() {
if (TestInternet() != "We are connected to the Internet") {
MenuManager.PauseGame ();
noInternetCanvas.SetActive (true);
StartCoroutine (PauseBeforeCheckingConnectionAgain);
} else {
noInternetCanvas.SetActive (false);
MenuManager.ResumeGame ();
}
}
public string TestInternet(string testSite = "http://google.com", string testHtmlString = "schema.org/WebPage") {
Debug.Log ("Testing internet at " + Time.realtimeSinceStartup.ToString());
string htmlText = GetHtmlFromURL (testSite);
if (htmlText == "No connection") {
return "No connection";
} else if (!htmlText.Contains (testHtmlString)) {");
return CheckInternetRedirectedLink ();
} else {
Debug.Log ("We are connected to the Internet from TestInternet at " + Time.realtimeSinceStartup.ToString());
return "We are connected to the Internet";
}
}
public string GetHtmlFromURL(string resource) {
string html = string.Empty;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (resource);
try {
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) {
bool isSuccess = (int)webResponse.StatusCode < 299 && (int)webResponse.StatusCode >= 200;
if (isSuccess) {
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())){
char[] chars = new char[80];
reader.Read(chars,0, chars.Length);
foreach(char ch in chars) {
html += ch;
}
}
}
}
}
catch {
return "No connection";
}
return html;
}
Any help would be appreciated, thank you!
Comment