IEnumerator connectToNATFacilitatorTest()
    {
        StartupResult startResult = rakPeerTest.Startup(2, new SocketDescriptor(), 1);

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

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

        Packet packet;

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

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

        guidTest = rakPeerTest.GetMyGUID().g.ToString();
        Debug.Log("Connected 2: " + guidTest);

        facilitatorSystemAddressTest = packet.systemAddress;

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

        rakPeerTest.SetMaximumIncomingConnections(2);

        if (firstTimeConnectTest)
        {
            firstTimeConnectTest = false;

            natPunchthroughClientTest = new NatPunchthroughClient();
            rakPeerTest.AttachPlugin(natPunchthroughClientTest);

            natPunchthroughClientTest.FindRouterPortStride(facilitatorSystemAddressTest);
        }
        else
        {
            StartCoroutine("waitForIncomingNATPunchThroughOnServerTest");
        }
        connectedToFacTest = true;

        isReadyTest = true;
    }
Exemplo n.º 2
0
    /**
     * Connect to the externally hosted NAT Facilitator (NATCompleteServer from the RakNet samples)
     * This is called initially and also after each succesfull punchthrough received on the server.
     */
    IEnumerator connectToNATFacilitator()
    {
        // Start the RakNet interface listening on a random port
        // We never need more than 2 connections, one to the Facilitator and one to either the server or the latest incoming client
        // Each time a client connects on the server RakNet is shut down and restarted with two fresh connections
        StartupResult startResult = rakPeer.Startup(2, new SocketDescriptor(), 1);

        if (startResult != StartupResult.RAKNET_STARTED)
        {
            Debug.Log("Failed to initialize network interface: " + startResult.ToString());
            yield break;
        }

        // Connect to the Facilitator
        ConnectionAttemptResult connectResult = rakPeer.Connect(facilitatorIP, (ushort)facilitatorPort, null, 0);

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

        // Connecting, wait for response
        Packet packet;

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

        // Was the connection accepted?
        if (packet.data[0] != (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED)
        {
            Debug.Log("Failed to connect to NAT Facilitator: " + ((DefaultMessageIDTypes)packet.data[0]));
            yield break;
        }

        // Success, we are connected to the Facilitator
        guid = rakPeer.GetMyGUID().g.ToString();
        Debug.Log("Connected: " + guid);

        // We store this for later so that we can tell which incoming messages are coming from the facilitator
        facilitatorSystemAddress = packet.systemAddress;

        // Now that we have an external connection we can get the externalIP
        externalIP = rakPeer.GetExternalID(packet.systemAddress).ToString(false);

        if (firstTimeConnect)
        {
            firstTimeConnect = false;

            // Attach RakNet punchthrough client
            // This is really what does all the heavy lifting
            natPunchthroughClient = new NatPunchthroughClient();
            rakPeer.AttachPlugin(natPunchthroughClient);
            // Punchthrough can't happen until RakNet is done finding router port stride
            // so we start it asap. If we didn't call this here RakNet would handle it
            // when we actually try and punch through.
            natPunchthroughClient.FindRouterPortStride(facilitatorSystemAddress);
        }
        else
        {
            // If this is not the first time connecting to the facilitor it means the server just received
            // a successful punchthrough and it reconnecting to prepare for more punching. We can start
            // listening immediately.
            StartCoroutine(waitForIncomingNATPunchThroughOnServer(onHolePunched));
        }

        isReady = true;
    }
    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;
    }
Exemplo n.º 4
0
        static int Main(string[] args)
        {
            char ch;
            string userInput;

            rakPeer = RakNetworkFactory.GetRakPeerInterface();

            rakPeer.AttachPlugin(replicaManager);

            rakPeer.SetNetworkIDManager(networkIDManager);

            replicaManager.SetAutoParticipateNewConnections(true);

            replicaManager.SetAutoConstructToNewParticipants(true);

            replicaManager.SetAutoSerializeInScope(true);

            replicaManager.SetReceiveConstructionCB(IntPtr.Zero, ConstructionCB);

            replicaManager.SetDownloadCompleteCB(IntPtr.Zero, SendDownloadCompleteCB, IntPtr.Zero, ReceiveDownloadCompleteCB);

            StringTable.Instance().AddString("Player", true);
            StringTable.Instance().AddString("Monster", true);

            Console.Write("Demonstration of ReplicaManager for client / server\n");
            Console.Write("The replica manager provides a framework to make it easier to synchronize\n");
            Console.Write("object creation, destruction, and member object updates\n");
            Console.Write("Difficulty: Intermediate\n\n");
            Console.Write("Run as (s)erver or (c)lient? ");
            userInput = Console.ReadLine();
            if (userInput[0] == 's' || userInput[0] == 'S')
            {
                isServer = true;
                SocketDescriptor socketDescriptor = new SocketDescriptor(60000, string.Empty);
                rakPeer.Startup(8, 0, new SocketDescriptor[] { socketDescriptor }, 1);
                rakPeer.SetMaximumIncomingConnections(8);
                Console.Write("Server started.\n");
            }
            else
            {
                isServer = false;
                SocketDescriptor socketDescriptor = new SocketDescriptor();
                rakPeer.Startup(1, 0, new SocketDescriptor[] { socketDescriptor }, 1);
                Console.Write("Enter IP to connect to: ");
                userInput = Console.ReadLine();
                if (userInput.Equals(string.Empty))
                {
                    userInput = "127.0.0.1";
                    Console.Write("{0}\n", userInput);
                }
                if (!rakPeer.Connect(userInput, 60000, string.Empty, 0))
                {
                    Console.Write("Connect call failed!\n");
                    return 1;
                }
                Console.Write("Connecting...\n");
            }

            // The network ID manager will automatically index pointers of object instance NetworkIDObject if
            // SetIsNetworkIDAuthority is called with true.  Otherwise, it will rely on another system setting the IDs
            networkIDManager.SetIsNetworkIDAuthority(isServer);

            Console.Write("Commands:\n(Q)uit\n(Space) Show status\n(R)andomize health and position\n");
            if (isServer)
            {
                Console.Write("Toggle (M)onster\nToggle (p)layer\n");
                Console.Write("Toggle (S)cope of player\n");
            }

            Packet p;

            while (true)
            {
                p = rakPeer.Receive();
                while (p != null)
                {
                    byte[] data = p.data;  // The access to data member had better reduce it. Copying occurs by this.
                    if (data[0] == RakNetBindings.ID_DISCONNECTION_NOTIFICATION || data[0] == RakNetBindings.ID_CONNECTION_LOST)
                    {
                        if (isServer)
                        {
                            Console.Write("Server connection lost.  Deleting objects\n");
                            if (monster != null)
                            {
                                monster.Dispose();
                            }
                            if (player != null)
                            {
                                player.Dispose();
                            }
                        }
                    }
                    rakPeer.DeallocatePacket(p);
                    p = rakPeer.Receive();
                }

                if (_kbhit() != 0)
                {
                    ch = Console.ReadKey(true).KeyChar;
                    if (ch == 'q' || ch == 'Q')
                    {
                        Console.Write("Quitting.\n");
                        break;
                    }
                    else if (ch == ' ')
                        ShowStatus(monster, player);
                    else if (ch == 'r' || ch == 'R')
                    {
                        if (player != null)
                        {
                            player.health = (int)RakNetBindings.randomMT();
                            player.position = (int)RakNetBindings.randomMT();

                            replicaManager.SignalSerializeNeeded(player.replica, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true);
                        }
                        if (monster != null)
                        {
                            monster.health = (int)RakNetBindings.randomMT();
                            monster.position = (int)RakNetBindings.randomMT();

                            replicaManager.SignalSerializeNeeded(monster.replica, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true);
                        }
                        Console.Write("Randomized player and monster health and position\n");
                        ShowStatus(monster, player);
                    }
                    else if (isServer)
                    {
                        if (ch == 'm' || ch == 'M')
                        {
                            if (monster == null)
                            {
                                Console.Write("Creating monster\n");
                                monster = new Monster();
                            }
                            else
                            {
                                monster.Dispose();
                                Console.Write("Deleted monster\n");
                                monster = null;
                            }
                        }
                        else if (ch == 'p' || ch == 'P')
                        {
                            if (player == null)
                            {
                                Console.Write("Creating player\n");
                                player = new Player();

                            }
                            else
                            {
                                player.Dispose();
                                Console.Write("Deleted player\n");
                                player = null;
                            }
                        }
                        else if (ch == 's' || ch == 'S')
                        {
                            if (player != null)
                            {
                                bool currentScope;
                                currentScope = replicaManager.IsInScope(player.replica, rakPeer.GetSystemAddressFromIndex(0));
                                if (currentScope == false)
                                    Console.Write("Setting scope for player to true for all remote systems.\n");
                                else
                                    Console.Write("Setting scope for player to false for all remote systems.\n");
                                replicaManager.SetScope(player.replica, !currentScope, RakNetBindings.UNASSIGNED_SYSTEM_ADDRESS, true);
                            }
                            else
                            {
                                Console.Write("No player to set scope for\n");
                            }
                        }
                    }
                }
                System.Threading.Thread.Sleep(30);
            }

            if (monster != null)
                monster.Dispose();
            if (player != null)
                player.Dispose();
            RakNetworkFactory.DestroyRakPeerInterface(rakPeer);

            return 1;
        }