没有互联网时 WWW 冻结

2024-01-29

我正在 Unity 中编写一个简单的代码,以检查我是否能够通过我的应用程序访问网站。这是我写的代码:

IEnumerator CheckInternetPing()
{
    WWW wwwInternet = new WWW("http://google.com");
    yield return wwwInternet;
    if (wwwInternet.bytesDownloaded == 0)
    {
        //yield return new WaitForSeconds(1f);
        Debug.Log("Not Connected to Internet");
    }
    else
    {
        Debug.Log("Connected to Internet");
        internetMenu.SetActive(false);
    }
}

我发现了一个错误,如果我在打开互联网的情况下运行此应用程序,它会显示“已连接”,但是当我关闭互联网并立即运行该应用程序时,它不会记录任何内容。仅当我再次重新启动应用程序时,它才会显示“未连接”。 有谁知道为什么它第一次不记录任何内容?谢谢


这是一个bugWWW类并且已经在这里很长时间了。每个设备的行为可能有所不同。如果 Wifi 被禁用,它曾经在编辑器上冻结。快速测试表明该错误尚未修复。

你需要使用HttpWebRequest代替WWW.

在下面的例子中,Thread用于避免请求阻塞Unity程序并且UnityThread用于在请求完成时回调到 Unity 主线程。得到UnityThread from this https://stackoverflow.com/questions/41330771/use-unity-api-from-another-thread-or-call-a-function-in-the-main-thread/41333540#41333540 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);
        });

    });
}

您需要扩展类changeSysTemHeader函数允许“用户代理”要更改的标题:

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);
    }
}

使用起来非常简单:

void Start()
{
    isOnline((online) =>
    {
        if (online)
        {
            Debug.Log("Connected to Internet");
            //internetMenu.SetActive(false);
        }
        else
        {
            Debug.Log("Not Connected to Internet");
        }
    });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

没有互联网时 WWW 冻结 的相关文章

随机推荐