WWW freezing when there is no internet

≡放荡痞女 提交于 2019-12-06 04:35:57

This is a bug with the WWW class and has been here for a long time. The behavior is probably different every device. It used to freeze on the Editor if Wifi is disabled. A quick test showed that this bug has not been fixed.

You need to use HttpWebRequest instead of WWW.

In the example below, Thread is used to avoid the request blocking Unity program and UnityThread is used to make callback into Unity main Thread when the request is done. Get UnityThread from this post.

void Awake()
{
    //Enable Callback on the main Thread
    UnityThread.initUnityThread();
}

void isOnline(Action<bool> online)
{
    bool success = true;

    //Use ThreadPool to avoid freezing
    ThreadPool.QueueUserWorkItem(delegate
    {
        try
        {
            int timeout = 2000;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com");
            request.Method = "GET";
            request.Timeout = timeout;
            request.KeepAlive = false;

            request.ServicePoint.Expect100Continue = false;
            request.ServicePoint.MaxIdleTime = timeout;

            //Make sure Google don't reject you when called on mobile device (Android)
            request.changeSysTemHeader("User-Agent", "Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response == null)
            {
                success = false;
            }

            if (response != null && response.StatusCode != HttpStatusCode.OK)
            {
                success = false;
            }
        }
        catch (Exception)
        {
            success = false;
        }

        //Do the callback in the main Thread
        UnityThread.executeInUpdate(() =>
        {
            if (online != null)
                online(success);
        });

    });
}

You need the extension class for the changeSysTemHeader function that allows the "User-Agent" header to be changed:

public static class ExtensionMethods
{
    public static void changeSysTemHeader(this HttpWebRequest request, string key, string value)
    {
        WebHeaderCollection wHeader = new WebHeaderCollection();
        wHeader[key] = value;

        FieldInfo fildInfo = request.GetType().GetField("webHeaders",
                                                System.Reflection.BindingFlags.NonPublic
                                                   | System.Reflection.BindingFlags.Instance
                                                   | System.Reflection.BindingFlags.GetField);

        fildInfo.SetValue(request, wHeader);
    }
}

It is really simple to use:

void Start()
{
    isOnline((online) =>
    {
        if (online)
        {
            Debug.Log("Connected to Internet");
            //internetMenu.SetActive(false);
        }
        else
        {
            Debug.Log("Not Connected to Internet");
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!