IEnumerator WaitDiscover()
    {
        NatDiscoverer           disc = new NatDiscoverer();
        CancellationTokenSource cts  = new CancellationTokenSource();

        cts.CancelAfter(10000);
        int gamePort = NATNetworkManager_PHP.singleton.myPort;
        Task <NatDevice> deviceTask = disc.DiscoverDeviceAsync(PortMapper.Upnp, cts);

        //deviceTask.RunSynchronously ()
        while (!deviceTask.IsCompleted && !deviceTask.IsCanceled)
        {
            yield return(new WaitForEndOfFrame());
        }
        if (deviceTask.IsCompleted)
        {
            bool hasException = false;
            try {
                device = deviceTask.Result;
            } catch (Exception ex) {
                Debug.Log("No Upnp. FurtherInfo :" + ex.ToString());
                hasException = true;
            }finally{
                if (!hasException && device != null)
                {
                    NATNetworkManager_PHP.DisplayLog("NAT DEVICE FOUND");
                    Task portMapTask = device.CreatePortMapAsync(new Mapping(Protocol.Udp, gamePort, gamePort));
                    //portMapTask.RunSynchronously ();
                    StartCoroutine("WaitUpnp", portMapTask);
                }
            }
        }
        yield return(new WaitForEndOfFrame());
    }
    IEnumerator WaitUpnp(Task portMapTask)
    {
        float cancelTime = Time.realtimeSinceStartup + 10;

        while (!portMapTask.IsCompleted && !portMapTask.IsCanceled && cancelTime > Time.realtimeSinceStartup)
        {
            yield return(new WaitForEndOfFrame());
        }
        hasUpnp = portMapTask.IsCompleted;
        NATNetworkManager_PHP.DisplayLog("HAS UPNP " + hasUpnp);
        if (!hasUpnp && !portMapTask.IsCanceled)
        {
            portMapTask.Dispose();
        }
    }
Esempio n. 3
0
 public void PasswordCheckClientReply(NetworkMessage msg)
 {
     NATNetworkManager_PHP.StringMsg parsed = msg.ReadMessage <NATNetworkManager_PHP.StringMsg> ();
     msg.conn.Disconnect();
     msg.conn.Dispose();
     if (!string.IsNullOrEmpty(parsed.value))
     {
         if (parsed.value == Network.player.ipAddress)
         {
             NATNetworkManager_PHP.singleton.networkAddress = "127.0.0.1";
         }
         else
         {
             NATNetworkManager_PHP.singleton.networkAddress = parsed.value;
         }
         NATNetworkManager_PHP.singleton.JoinLocal();
     }
     else
     {
         NATNetworkManager_PHP.DisplayLog("Wrong Password");
     }
 }
 IEnumerator WaitForNetwork()
 {
     for (int a = 0; a < 600; a++)
     {
         if (Application.internetReachability != NetworkReachability.NotReachable)
         {
             StartCoroutine("TestNAT");
             StartCoroutine("TestIP");
             StartCoroutine("WaitDiscover");
             //StartCoroutine ("WaitForTest");
             //joinNet.SetActive (true);
             TryCoroutine();
             yield break;
         }
         yield return(new WaitForSecondsRealtime(0.1f));
     }
     if (Application.internetReachability == NetworkReachability.NotReachable)
     {
         NATNetworkManager_PHP.DisplayLog("Not connected to any network.");
         StartCoroutine("WaitForNetwork");
     }
 }
Esempio n. 5
0
    IEnumerator WaitForPassClientConnect(string pass)
    {
        float time = 0;

        while (!passClient.isConnected && time < 5)
        {
            yield return(new WaitForEndOfFrame());

            time += Time.deltaTime;
        }
        if (passClient.isConnected)
        {
            if (!passClient.handlers.ContainsKey(PassCheckId))
            {
                passClient.RegisterHandler(PassCheckId, PasswordCheckClientReply);
            }
            passClient.Send(PassCheckId, new NATNetworkManager_PHP.StringMsg(pass));
            NATNetworkManager_PHP.singleton.myRoom.roomPass = pass;
        }
        else
        {
            NATNetworkManager_PHP.DisplayLog("Connection Timed Out");
        }
    }
    IEnumerator waitForResponseFromServer(RakNetGUID hostGUID)
    {
        ushort natListenPort = 0, natConnectPort = 0;

        while (true)
        {
            Packet packet = rakPeer.Receive();
            if (packet != null)
            {
                DefaultMessageIDTypes messageType = (DefaultMessageIDTypes)packet.data[0];

                switch (messageType)
                {
                case DefaultMessageIDTypes.ID_NAT_PUNCHTHROUGH_SUCCEEDED:
                    // A hole has been punched but we're not done yet. We need to actually connect (via RakNet)
                    // to the server so that we can get the port to connect from
                    // natConnectPort is the external port of the server to connect to
                    natConnectPort = packet.systemAddress.GetPort();
                    rakPeer.Connect(packet.systemAddress.ToString(false), natConnectPort, "", 0);
                    Debug.Log("Hole punched!" + packet.systemAddress.GetPort());
                    break;

                case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                    // Ok, we connected, we can now use GetExternalID to get the port to connect from.
                    natListenPort = rakPeer.GetExternalID(packet.systemAddress).GetPort();
                    Debug.Log("Connected");
                    // Now we wait for the server to disconnect us so that we know it is ready for the UNet connection
                    break;

                case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                    // Server has disconnected us. We are ready to connect via UNet

                    // Shut down RakNet
                    rakPeer.Shutdown(0);
                    // Hole is punched!
                    onHolePunchedClient(natListenPort, natConnectPort);

                    //StartCoroutine(connectToNATFacilitator());

                    yield break;                     // Totally done

                case DefaultMessageIDTypes.ID_NAT_CONNECTION_TO_TARGET_LOST:
                {
                    NATNetworkManager_PHP.DisplayLog("target connection lost");                              //when two players conecting at same time
                    TryRepunch(hostGUID, packet.systemAddress);
                    yield break;
                }

                case DefaultMessageIDTypes.ID_NAT_TARGET_UNRESPONSIVE:
                {
                    NATNetworkManager_PHP.DisplayLog("unresponsive");                             //when three players conecting at same time
                    TryRepunch(hostGUID, packet.systemAddress);
                    yield break;
                }

                case DefaultMessageIDTypes.ID_NAT_PUNCHTHROUGH_FAILED:
                {
                    NATNetworkManager_PHP.DisplayLog("fail");                              //when two players conecting at same time
                    TryRepunch(hostGUID, packet.systemAddress);
                    yield break;
                }

                case DefaultMessageIDTypes.ID_NAT_TARGET_NOT_CONNECTED:
                {
                    NATNetworkManager_PHP.DisplayLog("target not connected");                             //when two players conecting at same time
                    TryRepunch(hostGUID, packet.systemAddress);
                    yield break;
                }

                case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:
                {
                    NATNetworkManager_PHP.DisplayLog("no free incoming connections");                             //when three players conecting at same time
                    TryRepunch(hostGUID, packet.systemAddress);
                    yield break;
                }

                default:
                    NATNetworkManager_PHP.DisplayLog("RakNet Client received unexpected message type: " + ((DefaultMessageIDTypes)packet.data[0]).ToString());
                    yield break;
                }
            }
            yield return(new WaitForEndOfFrame());
        }
    }
    IEnumerator connectToNATFacilitator()
    {
        StartupResult startResult = rakPeer.Startup(2, new SocketDescriptor(), 1);

        if (startResult != StartupResult.RAKNET_STARTED)
        {
            NATNetworkManager_PHP.DisplayLog("Failed to initialize network interface: " + startResult.ToString());
            yield break;
        }
        ConnectionAttemptResult connectResult = rakPeer.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0);

        if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED)
        {
            NATNetworkManager_PHP.DisplayLog("Failed to initialize connection to NAT Facilitator: " + connectResult.ToString());
            yield break;
        }

        Packet packet;

        while ((packet = rakPeer.Receive()) == null)
        {
            yield return(new WaitForEndOfFrame());
        }

        if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED)
        {
            NATNetworkManager_PHP.DisplayLog("Failed to connect to NAT Facilitator: " + ((DefaultMessageIDTypes)packet.data[0]));
            NATNetworkManager_PHP.RefreshInfo();
            yield break;
        }

        guid = rakPeer.GetMyGUID().g.ToString();
        Debug.Log("Connected: " + guid);


        externalIP = rakPeer.GetExternalID(packet.systemAddress).ToString(false);

        NATNetworkManager_PHP.RefreshInfo();



        //if (firstTimeConnect) {
        //	firstTimeConnect = false;
        natPunchthroughClient = new NatPunchthroughClient();
        rakPeer.AttachPlugin(natPunchthroughClient);

        natPunchthroughClient.FindRouterPortStride(packet.systemAddress);
        facilitatorSystemAddress = packet.systemAddress;

        /*} else {
         *      rakPeer.AttachPlugin (natPunchthroughClient);
         *      //if (!facilitatorSystemAddress.EqualsExcludingPort(packet.systemAddress)) {
         *              natPunchthroughClient.FindRouterPortStride (packet.systemAddress);
         *      //}
         *      facilitatorSystemAddress = packet.systemAddress;
         * }*/
        if (NetworkServer.active && NATNetworkManager_PHP.singleton.myRoom.isNetGame)
        {
            StartCoroutine("waitForIncomingNATPunchThroughOnServer");
        }

        if (string.IsNullOrEmpty(guid))
        {
            NATNetworkManager_PHP.DisplayLog("GUID IS NULL OR EMPTY");
        }
        else
        {
            NATNetworkManager_PHP.singleton.StartCoroutine("setNewGUID", guid);
        }

        NATNetworkManager_PHP.connectedToFac = true;
        rakPeer.SetMaximumIncomingConnections(2);
        isReady = true;
    }
    IEnumerator WaitForRaknet()
    {
        for (int a = 0; a < 600; a++)
        {
            bool testDone = false;
            if (ipStatus != ConnectionTesterStatus.Undetermined && natStatus != ConnectionTesterStatus.Undetermined)
            {
                testDone = true;
            }
            if (ipStatus == ConnectionTesterStatus.Error)
            {
                ipStatus = ConnectionTesterStatus.Undetermined;
                testDone = false;
                Network.TestConnection(true);
                StartCoroutine("TestIP");
            }
            if (natStatus == ConnectionTesterStatus.Error)
            {
                natStatus = ConnectionTesterStatus.Undetermined;
                testDone  = false;
                Network.TestConnectionNAT(true);
                StartCoroutine("TestNAT");
            }
            if (NATNetworkManager_PHP.connectedToFac && testDone)
            {
                if (ipStatus == ConnectionTesterStatus.PublicIPIsConnectable || ipStatus == ConnectionTesterStatus.PublicIPNoServerStarted)
                {
                    natCapability = NATCapabilityIndex.publicIPPortOpen;
                }
                else if (hasUpnp)
                {
                    natCapability = NATCapabilityIndex.upnp;
                }
                else
                {
                    switch (ipStatus)
                    {
                    case ConnectionTesterStatus.NATpunchthroughFullCone:
                    {
                        natCapability = NATCapabilityIndex.natFullCone;
                        break;
                    }

                    case ConnectionTesterStatus.NATpunchthroughAddressRestrictedCone:
                    {
                        natCapability = NATCapabilityIndex.natAddressRestricted;
                        break;
                    }

                    case ConnectionTesterStatus.LimitedNATPunchthroughPortRestricted:
                    {
                        natCapability = NATCapabilityIndex.natPortRestricted;
                        break;
                    }

                    case ConnectionTesterStatus.LimitedNATPunchthroughSymmetric:
                    {
                        natCapability = NATCapabilityIndex.natSymmetrical;
                        break;
                    }
                    }
                }
                if (!connectedToFacTest)
                {
                    ConnectFacTest();
                }
                StartCoroutine("WaitForRaknetTest");
                yield break;
            }
            yield return(new WaitForSecondsRealtime(0.1f));
        }
        if (!NATNetworkManager_PHP.connectedToFac)
        {
            NATNetworkManager_PHP.DisplayLog("ConnectFac failed");
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                StartCoroutine("WaitForNetwork");
            }
            else
            {
                TryCoroutine();
            }
        }
    }