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
    public void StartClient()
    {
        OnApplicationQuit();

        client = RakPeerInterface.GetInstance();

        SocketDescriptor socketDescriptor = new SocketDescriptor(Convert.ToUInt16(UnityEngine.Random.Range(81, 65536)), "0");

        socketDescriptor.socketFamily = 2;

        client.Startup(8, socketDescriptor, 1);
        client.SetOccasionalPing(true);

        ConnectionAttemptResult car = client.Connect(input_IP.text, Convert.ToUInt16(input_PORT.text), "Rumpelstiltskin", "Rumpelstiltskin".Length);

        if (car != RakNet.ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED)
        {
            Debug.LogError(car);
        }

        Debug.LogWarning("My IP Addresses:");
        for (uint i = 0; i < client.GetNumberOfAddresses(); i++)
        {
            Debug.LogWarning(client.GetLocalIP(i).ToString());
        }
        Debug.LogWarning("My GUID is " + client.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString());
    }
Exemplo n.º 3
0
 public void initialize()
 {
     peer.Startup(1, new SocketDescriptor(port, ""), 1);
     Console.WriteLine("Starting the client.");
     // 90.229.195.46
     peer.Connect("172.18.5.57", 60000, "0", 0);
 }
        public Task <IConnection> Connect(string endpoint)
        {
            logger.Debug("Connecting to endpoint {0}", endpoint);

            if (_peer == null || !_peer.IsActive())
            {
                throw new InvalidOperationException("Transport not started. Call Start before connect.");
            }

            var infos      = endpoint.Split(':');
            var portString = infos[infos.Length - 1];
            var port       = ushort.Parse(portString);

            var host = endpoint.Substring(0, endpoint.Length - portString.Length - 1);


            var tcs = new TaskCompletionSource <IConnection>();
            var pendingConnection = new PendingConnection(new SystemAddress(host, port).ToString(), tcs);

            _pendingConnections.Enqueue(pendingConnection);

            lock (_connectionTask)
            {
                _connectionTask = _connectionTask.ContinueWith(t =>
                {
                    var connectResult = _peer.Connect(host, port, null, 0);

                    if (connectResult != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED)
                    {
                        throw new Exception("Raknet connection failed: " + connectResult);
                    }
                    return(tcs.Task);
                }).Unwrap();

                return(_connectionTask);
            }



            //for (int i = 0; i < 1; i++)
            //{
            //    UnityEngine.Debug.Log("before Fix for ip");
            //    var sa = _peer.GetMyBoundAddress(i);
            //    address.FixForIPVersion(sa);
            //    var str = address.ToString();
            //    UnityEngine.Debug.Log("address = " + str);

            //}



            //var ips = Dns.GetHostAddresses(host);
        }
Exemplo n.º 5
0
        public Task <IConnection> Connect(string endpoint)
        {
            if (_peer == null || !_peer.IsActive())
            {
                throw new InvalidOperationException("Transport not started. Call Start before connect.");
            }
            var infos  = endpoint.Split(':');
            var host   = infos[0];
            var port   = ushort.Parse(infos[1]);
            var result = _peer.Connect(host, port, null, 0);

            var address = new SystemAddress(host, port);

            var tcs = new TaskCompletionSource <IConnection>();

            _pendingConnections.TryAdd(address.ToString(), tcs);

            return(tcs.Task);
        }
Exemplo n.º 6
0
    public bool Connect(string ip, int port, string pwd)
    {
        m_Socket = RakPeerInterface.GetInstance();
        m_Socket.AllowConnectionResponseIPMigration(false);
        SocketDescriptor socketDescriptor = new SocketDescriptor(0, "0");

        socketDescriptor.socketFamily = 2;
        m_Socket.Startup(8, socketDescriptor, 1);
        m_Socket.SetOccasionalPing(true);
        ConnectionAttemptResult car = m_Socket.Connect(ip, (ushort)port, pwd, pwd.Length);

        if (car == ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED)
        {
            return(true);
        }
        else
        {
            m_Socket.Shutdown(300);
            RakPeerInterface.DestroyInstance(m_Socket);
            return(false);
        }
    }
Exemplo n.º 7
0
        internal static void Connect()
        {
            try
            {
                if (isConnected || isConnecting)
                {
                    return;
                }

                isConnecting = true;

                ConnectionAttemptResult res = clientInterface.Connect(Program.ServerIP, Program.ServerPort, Program.Password, Program.Password == null ? 0 : Program.Password.Length);
                if (res != ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED)
                {
                    throw new Exception("Connection couldn't be established: " + res);
                }

                Logger.Log("Connection attempt {0} to '{1}:{2}' started.", ++connectionAttempts, Program.ServerIP, Program.ServerPort);
            }
            catch (Exception e)
            {
                Logger.LogError("Connection failed! " + e);
            }
        }
Exemplo n.º 8
0
        public void Connect(String ip, ushort port, String pw)
        {
            if (isConnected || lastConnectionTry + 10000 * 100 > DateTime.Now.Ticks)
            {
                return;
            }
            if (connectionTrys >= 100)
            {
                zERROR.GetZErr(Process.ThisProcess()).Report(4, 'G', "Verbindung nicht möglich!", 0, "Client.cs", 0);
            }
            this.ip = ip; this.port = port; this.pw = pw;
            bool b;

            pw = "ver2.081" + pw;
            b  = client.Connect(ip, port, pw, pw.Length) == ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED;
            client.SetOccasionalPing(true);
            if (!b)
            {
                zCView.GetStartscreen(Process.ThisProcess()).PrintTimedCXY("The connection could not be estabilshed", 10, 255, 0, 0, 255);
                zERROR.GetZErr(Process.ThisProcess()).Report(2, 'G', "Es konnte keine Verbindung aufgebaut werden.", 0, "Client.cs", 0);
            }
            connectionTrys++;
            lastConnectionTry = DateTime.Now.Ticks;
        }
Exemplo n.º 9
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;
    }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            if (!File.Exists("RakNet.dll"))
            {
                Console.WriteLine("The SWIG build of the DLL has not been copied to the executable directory\nCopy from Swig/SwigWindowsCSharpSample/SwigTestApp/bin/X86/Debug/RakNet.dll to\nSwigWindowsCSharpSample/SwigTestApp/bin/Debug/RakNet.dll\nPress enter to quit.");
                Console.Read();
                return;
            }

            try
            {
                RakString dllCallTest = new RakString();
            }
            catch (Exception e)
            {
                Console.WriteLine("DLL issue\nMake sure RakNetWrap.cxx is included in the DLL project.\nPress enter to quit.");
                Console.Read();
                return;
            }

            Packet    testPacket;
            int       loopNumber;
            BitStream stringTestSendBitStream    = new BitStream();
            BitStream rakStringTestSendBitStream = new BitStream();
            BitStream receiveBitStream           = new BitStream();
            String    holdingString;
            TimeSpan  startTimeSpan;
            RakString rakStringTest = new RakString();

            RakPeerInterface testClient = RakPeer.GetInstance();

            testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1);

            RakPeerInterface testServer = RakPeer.GetInstance();

            testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1);
            testServer.SetMaximumIncomingConnections(1);

            Console.WriteLine("Send and receive loop using BitStream.\nBitStream read done into RakString");

            testClient.Connect("127.0.0.1", 60001, "", 0);

            String sendString = "The test string";

            stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM);
            stringTestSendBitStream.Write(sendString);

            RakString testRakString = new RakString("Test RakString");

            rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM);
            rakStringTestSendBitStream.Write(testRakString);

            startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            loopNumber    = 0;

            while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
            {
                testPacket = testServer.Receive();
                if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    receiveBitStream.Reset();
                    receiveBitStream.Write(testPacket.data, testPacket.length);
                    receiveBitStream.IgnoreBytes(1);
                    receiveBitStream.Read(rakStringTest);
                    Console.WriteLine("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String());
                }
                testServer.DeallocatePacket(testPacket);
                loopNumber++;
                System.Threading.Thread.Sleep(50);
                testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false);
            }

            Console.WriteLine("String send and receive loop using BitStream.\nBitStream read done into String");

            SystemAddress[] remoteSystems;
            ushort          numberOfSystems = 1;

            testServer.GetConnectionList(out remoteSystems, ref numberOfSystems);

            startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            loopNumber    = 0;
            while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
            {
                testPacket = testServer.Receive();
                if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    receiveBitStream.Reset();
                    receiveBitStream.Write(testPacket.data, testPacket.length);
                    receiveBitStream.IgnoreBytes(1);
                    receiveBitStream.Read(out holdingString);
                    Console.WriteLine("Loop number: " + loopNumber + "\nData: " + holdingString);
                }
                testServer.DeallocatePacket(testPacket);
                loopNumber++;
                System.Threading.Thread.Sleep(50);
                testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false);
            }
            //If RakString is not freed before program exit it will crash
            rakStringTest.Dispose();
            testRakString.Dispose();

            RakPeer.DestroyInstance(testClient);
            RakPeer.DestroyInstance(testServer);
            Console.WriteLine("Demo complete. Press Enter.");
            Console.Read();
        }
    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.º 12
0
    // Use this for initialization
    void Start()
    {
        try
        {
            RakString dllCallTest = new RakString();
        }
        catch (Exception e)
        {
            Debug.Log("DLL issue\nAdd SwigOutput/CplusDLLIncludes/RakNetWrap.cxx to the project\nDLL_Swig/RakNet.sln and rebuild.\nPress enter to quit.");
            return;
        }

        Packet testPacket;
        int    loopNumber;

        RakNet.BitStream stringTestSendBitStream    = new RakNet.BitStream();
        RakNet.BitStream rakStringTestSendBitStream = new RakNet.BitStream();
        RakNet.BitStream receiveBitStream           = new RakNet.BitStream();
        String           holdingString;
        TimeSpan         startTimeSpan;
        RakString        rakStringTest = new RakString();

        RakPeerInterface testClient = RakPeer.GetInstance();

        testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1);

        RakPeerInterface testServer = RakPeer.GetInstance();

        testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1);
        testServer.SetMaximumIncomingConnections(1);

        Console.WriteLine("Send and receive loop using BitStream.\nBitStream read done into RakString");

        testClient.Connect("127.0.0.1", 60001, "", 0);

        String sendString = "The test string";

        stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM);
        stringTestSendBitStream.Write(sendString);

        RakString testRakString = new RakString("Test RakString");

        rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM);
        rakStringTestSendBitStream.Write(testRakString);

        startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
        loopNumber    = 0;

        while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
        {
            testPacket = testServer.Receive();
            if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
            {
                receiveBitStream.Reset();
                receiveBitStream.Write(testPacket.data, testPacket.length);
                receiveBitStream.IgnoreBytes(1);
                receiveBitStream.Read(rakStringTest);
                Debug.Log("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String());
            }
            testServer.DeallocatePacket(testPacket);
            loopNumber++;
            System.Threading.Thread.Sleep(50);
            testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false);
        }

        Debug.Log("String send and receive loop using BitStream.\nBitStream read done into String");

        SystemAddress[] remoteSystems;
        ushort          numberOfSystems = 1;

        testServer.GetConnectionList(out remoteSystems, ref numberOfSystems);

        startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
        loopNumber    = 0;
        while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
        {
            testPacket = testServer.Receive();
            if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
            {
                receiveBitStream.Reset();
                receiveBitStream.Write(testPacket.data, testPacket.length);
                receiveBitStream.IgnoreBytes(1);
                receiveBitStream.Read(out holdingString);
                Debug.Log("Loop number: " + loopNumber + "\nData: " + holdingString);
            }
            testServer.DeallocatePacket(testPacket);
            loopNumber++;
            System.Threading.Thread.Sleep(50);
            SystemAddress sa = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS;
            testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false);
        }
        //If RakString is not freed before program exit it will crash
        rakStringTest.Dispose();
        testRakString.Dispose();

        RakPeer.DestroyInstance(testClient);
        RakPeer.DestroyInstance(testServer);
        Debug.Log("Demo complete. Press Enter.");
    }
Exemplo n.º 13
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;
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Packet    testPacket;
            int       loopNumber;
            BitStream stringTestSendBitStream    = new BitStream();
            BitStream rakStringTestSendBitStream = new BitStream();
            BitStream receiveBitStream           = new BitStream();
            String    holdingString;
            TimeSpan  startTimeSpan;
            RakString rakStringTest = new RakString();

            RakPeerInterface testClient = RakPeer.GetInstance();

            testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1);

            RakPeerInterface testServer = RakPeer.GetInstance();

            testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1);
            testServer.SetMaximumIncomingConnections(1);

            Console.WriteLine("Press enter to start RakString send and receive loop using BitStream.\nBitStream read done into RakString");
            Console.WriteLine("Loop will run for 15 seconds");
            Console.ReadLine();

            testClient.Connect("127.0.0.1", 60001, "", 0);

            String sendString = "The test string";

            stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM);
            stringTestSendBitStream.Write(sendString);

            RakString testRakString = new RakString("Test RakString");

            rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM);
            rakStringTestSendBitStream.Write(testRakString);

            startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            loopNumber    = 0;

            while (startTimeSpan.TotalSeconds + 15 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
            {
                testPacket = testServer.Receive();
                if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    receiveBitStream.Reset();
                    receiveBitStream.Write(testPacket.data, testPacket.length);
                    receiveBitStream.IgnoreBytes(1);
                    receiveBitStream.Read(rakStringTest);
                    Console.WriteLine("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String());
                }
                testServer.DeallocatePacket(testPacket);
                loopNumber++;
                System.Threading.Thread.Sleep(50);
                testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false);
            }

            Console.WriteLine("Press enter to start String send and receive loop using BitStream.\nBitStream read done into String");
            Console.WriteLine("Loop will run for 15 seconds");
            Console.ReadLine();

            startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1));
            loopNumber    = 0;
            while (startTimeSpan.TotalSeconds + 15 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
            {
                testPacket = testServer.Receive();
                if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    receiveBitStream.Reset();
                    receiveBitStream.Write(testPacket.data, testPacket.length);
                    receiveBitStream.IgnoreBytes(1);
                    receiveBitStream.Read(out holdingString);
                    Console.WriteLine("Loop number: " + loopNumber + "\nData: " + holdingString);
                }
                testServer.DeallocatePacket(testPacket);
                loopNumber++;
                System.Threading.Thread.Sleep(50);
                testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false);
            }
            //If RakString is not freed before program exit it will crash
            rakStringTest.Dispose();
            testRakString.Dispose();

            RakPeer.DestroyInstance(testClient);
            RakPeer.DestroyInstance(testServer);
            Console.WriteLine("Demo complete. Press Enter.");
            Console.Read();
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            RakNetStatistics rss    = new RakNetStatistics();
            RakPeerInterface client = RakPeerInterface.GetInstance();
            Packet           p      = new Packet();
            byte             packetIdentifier;
            bool             isServer = false;

            SystemAddress ClientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS;

            string ip, serverPort, clientPort;

            Console.WriteLine("This is a sample implementation of a text based chat client");
            Console.WriteLine("Connect to the project 'Chat Example Server'");

            Console.WriteLine("Enter the client port to listen on");
            clientPort = Console.ReadLine();
            if (clientPort.Length == 0)
            {
                clientPort = "0";
            }

            Console.WriteLine("Enter the IP to connect to");
            ip = Console.ReadLine();
            if (ip.Length == 0)
            {
                ip = "127.0.0.1";
            }

            Console.WriteLine("Enter the port to connect to");
            serverPort = Console.ReadLine();
            if (serverPort.Length == 0)
            {
                serverPort = "1234";
            }

            SocketDescriptor socketDescriptor = new SocketDescriptor(Convert.ToUInt16(clientPort), "0");

            socketDescriptor.socketFamily = AF_INET;

            client.Startup(8, socketDescriptor, 1);
            client.SetOccasionalPing(true);

            ConnectionAttemptResult car = client.Connect(ip, Convert.ToUInt16(serverPort), "Rumpelstiltskin", "Rumpelstiltskin".Length);

            if (car != RakNet.ConnectionAttemptResult.CONNECTION_ATTEMPT_STARTED)
            {
                throw new Exception();
            }

            Console.WriteLine("My IP Addresses:");
            for (uint i = 0; i < client.GetNumberOfAddresses(); i++)
            {
                Console.WriteLine(client.GetLocalIP(i).ToString());
            }
            Console.WriteLine("My GUID is " + client.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString());
            Console.WriteLine("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'disconnect' to disconnect. 'connect' to reconnnect. Type to talk.");
            string message;

            while (true)
            {
                System.Threading.Thread.Sleep(30);

                //Entire networking is threaded
                if (Console.KeyAvailable)
                {
                    message = Console.ReadLine();
                    if (message == "quit")
                    {
                        Console.WriteLine("Quitting");
                        break;
                    }

                    if (message == "stat")
                    {
                        string message2 = "";
                        rss = client.GetStatistics(client.GetSystemAddressFromIndex(0));
                        RakNet.RakNet.StatisticsToString(rss, out message2, 2);
                        Console.WriteLine(message2);
                        continue;
                    }

                    if (message == "disconnect")
                    {
                        Console.WriteLine("Enter index to disconnect: ");
                        string str = Console.ReadLine();
                        if (str == "")
                        {
                            str = "0";
                        }
                        uint index = Convert.ToUInt32(str, 16);
                        client.CloseConnection(client.GetSystemAddressFromIndex(index), false);
                        Console.WriteLine("Disconnecting");
                        continue;
                    }

                    if (message == "shutdown")
                    {
                        client.Shutdown(100);
                        Console.WriteLine("Disconnecting");
                        continue;
                    }

                    if (message == "ping")
                    {
                        if (client.GetSystemAddressFromIndex(0) != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS)
                        {
                            client.Ping(client.GetSystemAddressFromIndex(0));
                        }
                        continue;
                    }
                    if (message == "connect")
                    {
                        Console.WriteLine("Enter the IP to connect to");
                        ip = Console.ReadLine();
                        if (ip.Length == 0)
                        {
                            ip = "127.0.0.1";
                        }

                        Console.WriteLine("Enter the port to connect to");
                        serverPort = Console.ReadLine();
                        if (serverPort.Length == 0)
                        {
                            serverPort = "1234";
                        }

                        ConnectionAttemptResult car2 = client.Connect(ip, Convert.ToUInt16(serverPort), "Rumpelstiltskin", "Rumpelstiltskin".Length);

                        continue;
                    }
                    if (message == "getlastping")
                    {
                        if (client.GetSystemAddressFromIndex(0) != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS)
                        {
                            Console.WriteLine(client.GetLastPing(client.GetSystemAddressFromIndex(0)));
                        }

                        continue;
                    }

                    if (message.Length > 0)
                    {
                        client.Send(message, message.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true);
                    }
                }

                for (p = client.Receive(); p != null; client.DeallocatePacket(p), p = client.Receive())
                {
                    packetIdentifier = GetPacketIdentifier(p);
                    switch ((DefaultMessageIDTypes)packetIdentifier)
                    {
                    case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                        Console.WriteLine("ID_DISCONNECTION_NOTIFICATION");
                        break;

                    case DefaultMessageIDTypes.ID_ALREADY_CONNECTED:
                        Console.WriteLine("ID_ALREADY_CONNECTED with guid " + p.guid);
                        break;

                    case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                        Console.WriteLine("ID_INCOMPATIBLE_PROTOCOL_VERSION ");
                        break;

                    case DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION:
                        Console.WriteLine("ID_REMOTE_DISCONNECTION_NOTIFICATION ");
                        break;

                    case DefaultMessageIDTypes.ID_REMOTE_CONNECTION_LOST:     // Server telling the clients of another client disconnecting forcefully.  You can manually broadcast this in a peer to peer enviroment if you want.
                        Console.WriteLine("ID_REMOTE_CONNECTION_LOST");
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_BANNED:     // Banned from this server
                        Console.WriteLine("We are banned from this server.\n");
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                        Console.WriteLine("Connection attempt failed ");
                        break;

                    case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:
                        Console.WriteLine("Server is full ");
                        break;

                    case DefaultMessageIDTypes.ID_INVALID_PASSWORD:
                        Console.WriteLine("ID_INVALID_PASSWORD\n");
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_LOST:
                        // Couldn't deliver a reliable packet - i.e. the other system was abnormally
                        // terminated
                        Console.WriteLine("ID_CONNECTION_LOST\n");
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                        // This tells the client they have connected
                        Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED to %s " + p.systemAddress.ToString() + "with GUID " + p.guid.ToString());
                        Console.WriteLine("My external address is:" + client.GetExternalID(p.systemAddress).ToString());
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTED_PING:
                    case DefaultMessageIDTypes.ID_UNCONNECTED_PING:
                        Console.WriteLine("Ping from " + p.systemAddress.ToString(true));
                        break;

                    default:
                        Console.WriteLine(System.Text.Encoding.UTF8.GetString(p.data));
                        break;
                    }
                }
            }
            client.Shutdown(300);
            RakNet.RakPeerInterface.DestroyInstance(client);
            Console.Read();
        }