Unity3d检测当前网络环境wifi/3G/4G,以及对服务器的Ping操作
发表于2017-08-08
本篇文章给大家介绍的是Unity3d检测当前网络环境wifi/3G/4G,以及对服务器的Ping操作。主要用到两个Unity的API:一个是Application.internetReachability,用来获取当前网络类型!需要注意的是,这里只是判断出来当前设备的网络环境,并不代表能连接到互联网上!是否能连接到互联网上需要通过下面的ping去操作!
使用方法如下:
if (NetWorkTxt != null) { if(Application.internetReachability == NetworkReachability.NotReachable) NetWorkTxt.text = "当前网络:不可用"; else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork) NetWorkTxt.text = "当前网络:3G/4G"; else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork) NetWorkTxt.text = "当前网络 : WIFI"; }
另一个是Ping这个类,其实大多数人都会直接使用www去做了,但是这里用ping有个好处,就是你自己可以控制网络请求中断间隔时间,www默认的时间太长了,这里我使用2秒来作为检测时间,超过2秒就认为服务器无法访问!
使用方法如下:
C# private void CheckResServerNetWorkReady() { StopCoroutine(PingConnect()); StartCoroutine(PingConnect()); } IEnumerator PingConnect() { m_PingResServerState = PingState.PingIng; //ResServer IP string ResServerIP = GetCurrentNormalIP(); //Ping服务器 Ping ping = new Ping(ResServerIP); int nTime = 0; while (!ping.isDone) { yield return new WaitForSeconds(0.1f); if (nTime > 20) //2秒 { nTime = 0; Debug.Log("连接失败 : " + ping.time); m_PingResServerState = PingState.CanNotConnectServer; yield break; } nTime++; } if(ping.isDone) { yield return ping.time; m_PingResServerState = PingState.PingOK; Debug.Log("连接成功"); } }
如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引