当没有互联网时,WWW会冻结

时间:2018-02-22 11:08:24

标签: c# unity3d httprequest

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

A[999]

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

1 个答案:

答案 0 :(得分:4)

这是一个错误WWW类,已经存在了很长时间。每个设备的行为可能都不同。如果禁用Wifi,它曾用于冻结编辑器。快速测试显示此错误尚未修复。

您需要使用HttpWebRequest代替WWW

在下面的示例中,Thread用于避免请求阻止Unity程序,UnityThread用于在请求完成后回调Unity主线程。从this帖子获取UnityThread

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功能的扩展类,该功能允许更改“User-Agent”标头:

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