您的位置:首页 > 理论基础 > 计算机网络

网络:Unity3d检测当前网络环境wifi/3G/4G,以及对服务器的Ping操作

2017-11-23 14:37 531 查看
主要用到两个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) //
time 2 sec, OverTime 
       { 
           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("連線成功"); 
   } 
}

喜欢2





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: