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

来源:互联网 发布:js函数没有返回值 编辑:程序博客网 时间:2024/05/18 01:13
网络:Unity3d检测当前网络环境wifi/3G/4G,以及对服务器的Ping操作
    <div class="editor_content"><span style="color: rgb(69, 69, 69);">主要用到两个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(“連線成功”);

   }

}

阅读全文
0 0
原创粉丝点击