这一切都发生在Start()
是的,这是可能的,如果是这种情况,可以在一帧内完成。如果在Update 函数中的每一帧都执行此操作,我会非常气馁,但事实并非如此。如果这是在应用程序的开头完成的,那很好。如果在游戏运行时这样做,将会影响性能。
但是这样的操作需要几秒钟
这样设计是为了避免阻塞主线程。
网络操作应在Thread 或async 方法中完成,以避免阻塞主线程。这就是大多数 Unity 网络 API(例如 WWW 和 UnityWebRequest)的工作方式。他们在后台使用Thread,然后通过在帧上让出/等待协程函数中的协程函数直到网络请求完成,为您提供协程来管理该线程。
要在一帧中完成此操作,只需使用 HttpWebRequest 并提供一个服务器 url 来检查。大多数示例使用google.com,因为它始终在线,但确保提供“User-Agent”,这样移动设备上的连接就不会被拒绝。最后,如果HttpStatusCode不是200或者有异常就说明有问题,否则就认为是连通的。
bool isOnline()
{
bool success = true;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.com");
request.Method = "GET";
//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;
}
return success;
}
用于更改 User-Agent 的自定义 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);
}
}
Start 函数的简单用法在 one 框架中完成:
void Start()
{
Debug.Log(isOnline());
}