2014-06-22 6 views
4

유니티에 게임을 포팅 할 때 Unity에서 인터넷 연결 확인과 관련하여 도움이 필요합니다. Official Unity Documentation에 'Application.internetReachability를 사용하지 마십시오. 그래서 어떤 코드가 여기에서 작동하는지 혼란 스럽습니다. 포럼에서 눈에 띄는 솔루션을 찾지 못했습니다. iOS 및 Android에서 작동해야하는 Wi-Fi 또는 GPRS가 있는지 여부를 확인하고 싶습니다. 미리 감사드립니다. 유니티 인터넷 연결 가능 여부 확인

답변

19

솔루션

Application.internetReachability 당신이 필요합니다. 아마도 Ping과 관련하여 아마.

using UnityEngine; 

public class InternetChecker : MonoBehaviour 
{ 
    private const bool allowCarrierDataNetwork = false; 
    private const string pingAddress = "8.8.8.8"; // Google Public DNS server 
    private const float waitingTime = 2.0f; 

    private Ping ping; 
    private float pingStartTime; 

    public void Start() 
    { 
     bool internetPossiblyAvailable; 
     switch (Application.internetReachability) 
     { 
      case NetworkReachability.ReachableViaLocalAreaNetwork: 
       internetPossiblyAvailable = true; 
       break; 
      case NetworkReachability.ReachableViaCarrierDataNetwork: 
       internetPossiblyAvailable = allowCarrierDataNetwork; 
       break; 
      default: 
       internetPossiblyAvailable = false; 
       break; 
     } 
     if (!internetPossiblyAvailable) 
     { 
      InternetIsNotAvailable(); 
      return; 
     } 
     ping = new Ping(pingAddress); 
     pingStartTime = Time.time; 
    } 

    public void Update() 
    { 
     if (ping != null) 
     { 
      bool stopCheck = true; 
      if (ping.isDone) 
      { 
       if (ping.time >= 0) 
        InternetAvailable(); 
       else 
        InternetIsNotAvailable(); 
      } 
      else if (Time.time - pingStartTime < waitingTime) 
       stopCheck = false; 
      else 
       InternetIsNotAvailable(); 
      if (stopCheck) 
       ping = null; 
     } 
    } 

    private void InternetIsNotAvailable() 
    { 
     Debug.Log("No Internet :("); 
    } 

    private void InternetAvailable() 
    { 
     Debug.Log("Internet is available! ;)"); 
    } 
} 

는이 IP 주소를 받아에만 즉,

  1. 유니티의 ping이 모든 도메인 이름 확인을하지 않습니다 참고 :

    다음은 예입니다. 따라서 일부 플레이어가 인터넷에 액세스 할 수 있지만 DNS에 문제가있는 경우이 메서드는 인터넷에 연결되어 있다고 말합니다.

  2. 단지 핑 검사 일뿐입니다. 100 % 정확할 것으로 기대하지 마십시오. 드물기는하지만 잘못된 정보를 제공합니다.
+0

이미 확인했습니다. "참고 :이 속성을 사용하여 실제 연결을 결정하지 마십시오."라는 링크에 대한 공식 메모를 읽어보십시오. – stack

+1

이것이 내가'Ping와 함께 사용하면 ' –

+0

죄송하지만 어떤 링크 나 샘플 코드를 제공해 주시겠습니까? 나는 http://forum.unity3d.com/threads/how-can-you-tell-if-there-exists-a-network-connection-of-any-kind.68938/이 링크를 시도했지만 작동하지 않았다. – stack

1

온라인 상태임을 진정으로 알기 위해서는 "포털 검색"을 구현해야합니다. 공개 WiFi 로그인 페이지를 누르는 중. Application.internetReachability를 확인하거나 Ping을 일부 주소로 지정한다고해서 성공적으로 연결하거나 WWW 요청을 할 수있는 것은 아닙니다.

나는 Internet Reachability Verifier라는 쉬운 자산을 만들었습니다. 인터넷 액세스를 확인했는지 (WWW 요청을 수행 할 수 있는지 여부) 여부를 최신 상태로 유지합니다. 여기 더 많은 정보 : http://j.mp/IRVUN

1

나는 그것이 서버가 될 수 있는지 여부, 연결을 테스트하고 NAT 펀치를 통해 있는지 여부를 성공적으로 사용할 수 있습니다 Network.TestConnection입니다 무슨.

이것은 우리가 제공 한 샘플 코드입니다. 결과가 ConnectionTesterStatus.Error이면 인터넷에 접속할 기회가 없습니다.

var testStatus = "Testing network connection capabilities."; 
var testMessage = "Test in progress"; 
var shouldEnableNatMessage : String = ""; 
var doneTesting = false; 
var probingPublicIP = false; 
var serverPort = 9999; 
var connectionTestResult = ConnectionTesterStatus.Undetermined; 

// Indicates if the useNat parameter be enabled when starting a server 
var useNat = false; 

function OnGUI() { 
    GUILayout.Label("Current Status: " + testStatus); 
    GUILayout.Label("Test result : " + testMessage); 
    GUILayout.Label(shouldEnableNatMessage); 
    if (!doneTesting) 
     TestConnection(); 
} 

function TestConnection() { 
    // Start/Poll the connection test, report the results in a label and 
    // react to the results accordingly 
    connectionTestResult = Network.TestConnection(); 
    switch (connectionTestResult) { 
     case ConnectionTesterStatus.Error: 
      testMessage = "Problem determining NAT capabilities"; 
      doneTesting = true; 
      break; 

     case ConnectionTesterStatus.Undetermined: 
      testMessage = "Undetermined NAT capabilities"; 
      doneTesting = false; 
      break; 

     case ConnectionTesterStatus.PublicIPIsConnectable: 
      testMessage = "Directly connectable public IP address."; 
      useNat = false; 
      doneTesting = true; 
      break; 

     // This case is a bit special as we now need to check if we can 
     // circumvent the blocking by using NAT punchthrough 
     case ConnectionTesterStatus.PublicIPPortBlocked: 
      testMessage = "Non-connectable public IP address (port " + 
       serverPort +" blocked), running a server is impossible."; 
      useNat = false; 
      // If no NAT punchthrough test has been performed on this public 
      // IP, force a test 
      if (!probingPublicIP) { 
       connectionTestResult = Network.TestConnectionNAT(); 
       probingPublicIP = true; 
       testStatus = "Testing if blocked public IP can be circumvented"; 
       timer = Time.time + 10; 
      } 
      // NAT punchthrough test was performed but we still get blocked 
      else if (Time.time > timer) { 
       probingPublicIP = false;  // reset 
       useNat = true; 
       doneTesting = true; 
      } 
      break; 
     case ConnectionTesterStatus.PublicIPNoServerStarted: 
      testMessage = "Public IP address but server not initialized, "+ 
       "it must be started to check server accessibility. Restart "+ 
       "connection test when ready."; 
      break; 

     case ConnectionTesterStatus.LimitedNATPunchthroughPortRestricted: 
      testMessage = "Limited NAT punchthrough capabilities. Cannot "+ 
       "connect to all types of NAT servers. Running a server "+ 
       "is ill advised as not everyone can connect."; 
      useNat = true; 
      doneTesting = true; 
      break; 

     case ConnectionTesterStatus.LimitedNATPunchthroughSymmetric: 
      testMessage = "Limited NAT punchthrough capabilities. Cannot "+ 
       "connect to all types of NAT servers. Running a server "+ 
       "is ill advised as not everyone can connect."; 
      useNat = true; 
      doneTesting = true; 
      break; 

     case ConnectionTesterStatus.NATpunchthroughAddressRestrictedCone: 
     case ConnectionTesterStatus.NATpunchthroughFullCone: 
      testMessage = "NAT punchthrough capable. Can connect to all "+ 
       "servers and receive connections from all clients. Enabling "+ 
       "NAT punchthrough functionality."; 
      useNat = true; 
      doneTesting = true; 
      break; 

     default: 
      testMessage = "Error in test routine, got " + connectionTestResult; 
    } 
    if (doneTesting) { 
     if (useNat) 
      shouldEnableNatMessage = "When starting a server the NAT "+ 
       "punchthrough feature should be enabled (useNat parameter)"; 
     else 
      shouldEnableNatMessage = "NAT punchthrough not needed"; 
     testStatus = "Done testing"; 
    } 
} 
-1

이것은 인터넷 확인을 위해 이미 사용하고있는 간단한 해결책입니다. IOS와 Android 모두에서 작동합니다. 개선이 필요 할지도 모르지만 여기에 있습니다 :

public static bool InternetStatus() 
{ 
    if (Application.internetReachability != NetworkReachability.NotReachable) 
    { 
     return true; 
    }else{ 
     return false; 
    } 
} 
+0

Unity Docs가이 솔루션을 권장하지 않는다는 것이 이미 언급되어 있습니다. –