void TryRepunch(RakNetGUID hostGUID, SystemAddress address)
 {
     rakPeer.CancelConnectionAttempt(address);
     rakPeer.CloseConnection(hostGUID, false);
     StopCoroutine("waitForResponseFromServer");
     NATNetworkManager_PHP.singleton.StartCoroutine("getNewGUID");
 }
 private void OnRequestClose(RakNetConnection c)
 {
     if (_peer != null)
     {
         _peer.CloseConnection(c.Guid, true);
     }
 }
Пример #3
0
 internal static void Disconnect()
 {
     clientInterface.CloseConnection(clientInterface.GetSystemAddressFromIndex(0), true, 0);
     isConnected    = false;
     isConnecting   = false;
     isDisconnected = true;
     Client.ScriptObject.OnDisconnection(-1);
 }
 void TryRepunchTest(RakNetGUID hostGUID, SystemAddress address)
 {
     rakPeerTest.CancelConnectionAttempt(address);
     rakPeerTest.CloseConnection(hostGUID, false);
     StopCoroutine("waitForResponseFromServerTest");
     natPunchthroughClientTest.OpenNAT(hostGUID, facilitatorSystemAddressTest);
     StartCoroutine("waitForResponseFromServerTest", hostGUID);
 }
Пример #5
0
 public void DisConnect()
 {
     m_Socket.CloseConnection(m_SystemAddress, false);
     m_Socket.Shutdown(300);
     RakPeerInterface.DestroyInstance(m_Socket);
     m_SystemAddress = null;
     m_Socket        = null;
     OnDisconnected();
 }
Пример #6
0
    /**
     * Wait for an incoming punchthrough from a client. Once a hole is punched
     * RakNet is shut down so that the NetworkManager can create a new UNet Server
     * listening on the port that the puncthrough arrived on.
     */
    IEnumerator waitForIncomingNATPunchThroughOnServer(Action <int> onHolePunched)
    {
        ushort natListenPort = 0;

        while (true)
        {
            yield return(new WaitForEndOfFrame());

            // Check for incoming packet
            Packet packet = rakPeer.Receive();

            // No packet, maybe next time
            if (packet == null)
            {
                continue;
            }

            // Got a packet, see what it is
            RakNet.DefaultMessageIDTypes messageType = (DefaultMessageIDTypes)packet.data[0];
            switch (messageType)
            {
            case DefaultMessageIDTypes.ID_NAT_PUNCHTHROUGH_SUCCEEDED:
                bool weAreTheSender = packet.data[1] == 1;
                if (!weAreTheSender)
                {
                    // Someone successfully punched through to us
                    // natListenPort is the port that the server should listen on
                    natListenPort = rakPeer.GetInternalID().GetPort();
                    // Now we're waiting for the client to try and connect to us
                    Debug.Log("Received punch through from " + rakPeer.GetMyGUID() + " " + packet.systemAddress.ToString());
                }
                break;

            case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION:
                // Cool we've got a connection. The client now knows which port to connect from / to
                Debug.Log("Received incoming RakNet connection.");
                // Close the connection to the client
                rakPeer.CloseConnection(packet.guid, true);
                // And also to the Facilitator
                rakPeer.CloseConnection(facilitatorSystemAddress, true);
                break;

            case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                // Once the Facilitator has disconnected we shut down raknet
                // so that UNet can listen on the port that RakNet is currently listening on
                // At this point the hole is succesfully punched
                // RakNet is then reconnected to the facilitator on a new random port.
                if (packet.systemAddress == facilitatorSystemAddress)
                {
                    rakPeer.Shutdown(0);

                    // Hole is punched, UNet can start listening
                    onHolePunched(natListenPort);

                    // Reconnect to Facilitator for next punchthrough
                    StartCoroutine(connectToNATFacilitator());

                    yield break;     // Totally done
                }
                break;

            default:
                Debug.Log(((DefaultMessageIDTypes)packet.data[0]).ToString());
                break;
            }
        }
    }
Пример #7
0
 public void Disconnect()
 {
     client.CloseConnection(client.GetSystemAddressFromIndex(0), true, 0);
     isConnected = false;
 }
Пример #8
0
        /**
         *   Game loop which receives data from clients and redirects/reacts accordingly.
         *   In this surrounding loop data is received from individual clients and the server reacts depending
         *   on the network message types (see class attributes for these types). This is done for each
         *   network message received by individual clients until there is no more (buffered) message
         *   left.
         */
        internal static void Update()
        {
            GameClient client = null;

            Packet packet;

            while ((packet = ServerInterface.Receive()) != null)
            {
                try
                {
                    clientDict.TryGetValue(packet.guid.g, out client);

                    pktReader.Load(packet.data, (int)packet.length);
                    ClientMessages id = (ClientMessages)pktReader.ReadByte();

                    switch (id)
                    {
                    case ClientMessages.RakNet_ConnectionLost:
                    case ClientMessages.RakNet_DisconnectionNotification:
                        if (client != null)
                        {
                            Logger.Log("Client disconnected: {0} IP: {1}", client.ID, client.SystemAddress);
                            DisconnectClient(client);
                        }
                        else
                        {
                            ServerInterface.CloseConnection(packet.guid, false);     //just to be sure
                        }
                        break;

                    case ClientMessages.RakNet_NewIncomingConnection:
                        if (client != null)     //there is already someone with this GUID. Should never happen.
                        {
                            throw new Exception("Duplicate RakNet-GUID! " + packet.guid);
                        }
                        else
                        {
                            Logger.Log("Client connected: IP: " + packet.systemAddress);
                        }
                        break;

                    default:
                        if (client == null)
                        {
                            if (id == ClientMessages.ConnectionMessage)     //sends mac & drive string, should always be sent first
                            {
                                if (GameClient.Messages.ReadConnection(pktReader, packet.guid, packet.systemAddress, out client))
                                {
                                    clientDict.Add(client.Guid.g, client);
                                    client.Create();
                                }
                                else
                                {
                                    Logger.LogWarning("Client was not allowed to connect: {0}", packet.systemAddress);
                                    ServerInterface.CloseConnection(packet.guid, false);
                                }
                            }
                            else
                            {
                                Logger.LogWarning("Client sent {0} before ConnectionMessage. Kicked IP: {1}", id, packet.systemAddress);
                                ServerInterface.CloseConnection(packet.guid, false);
                            }
                        }
                        else
                        {
                            if (id > ClientMessages.ScriptMessage && !client.IsIngame)
                            {
                                //Logger.LogWarning("Client sent {0} without being ingame. Kicked: {1} IP:{2}", msgID, p.guid, p.systemAddress);
                                //DisconnectClient(client);
                                break;
                            }
                            else
                            {
                                ReadUserMessage(id, client, pktReader);
                            }
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    if (packet.length > 0)
                    {
                        Logger.LogError("{0}: {1}: {2}\n{3}", (ClientMessages)packet.data[0], e.Source, e.Message, e.StackTrace);
                    }
                    else
                    {
                        Logger.LogError("{0}: {1}\n{2}", e.Source, e.Message, e.StackTrace);
                    }

                    if (client == null)
                    {
                        ServerInterface.CloseConnection(packet.guid, false);
                    }
                    else
                    {
                        DisconnectClient(client);
                    }
                }
                finally
                {
                    ServerInterface.DeallocatePacket(packet);
                }
            }
        }
Пример #9
0
 public void CloseConnection()
 {
     client.CloseConnection(client.GetSystemAddressFromIndex(0), false);
     client.Shutdown(300);
 }
Пример #10
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();
        }
Пример #11
0
        static void Main(string[] args)
        {
            RakNetStatistics rss    = new RakNetStatistics();
            RakPeerInterface server = RakPeerInterface.GetInstance();

            server.SetIncomingPassword("Rumpelstiltskin", "Rumpelstiltskin".Length);
            server.SetTimeoutTime(30000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS);

            Packet p = new Packet();

            RakNet.SystemAddress clientID = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS;
            byte packetIdentifier;
            bool isServer = true;

            string serverPort;

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

            Console.WriteLine("Starting server");
            RakNet.SocketDescriptor socketDescriptors = new SocketDescriptor(Convert.ToUInt16(serverPort), "0");
            socketDescriptors.port         = Convert.ToUInt16(serverPort);
            socketDescriptors.socketFamily = AF_INET;


            StartupResult sar = server.Startup(4, socketDescriptors, 1);

            if (sar != StartupResult.RAKNET_STARTED)
            {
                Console.WriteLine("Error starting server");
            }

            server.SetMaximumIncomingConnections(4);
            System.Threading.Thread.Sleep(1000);
            server.SetOccasionalPing(true);
            server.SetUnreliableTimeout(1000);


            for (int i = 0; i < server.GetNumberOfAddresses(); i++)
            {
                SystemAddress sa = server.GetInternalID(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, i);
                Console.WriteLine((i + 1).ToString() + ". " + sa.ToString() + "(LAN = " + sa.IsLANAddress() + ")");
            }
            Console.WriteLine("My GUID is " + server.GetGuidFromSystemAddress(RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS).ToString());
            Console.WriteLine("'quit' to quit. 'stat' to show stats. 'ping' to ping.\n'pingip' to ping an ip address\n'ban' to ban an IP from connecting.\n'kick to kick the first connected player.\nType to talk.");
            string message;

            while (true)
            {
                System.Threading.Thread.Sleep(30);
                if (Console.KeyAvailable)
                {
                    message = Console.ReadLine();

                    if (message == "quit")
                    {
                        Console.WriteLine("Quitting");
                        break;
                    }

                    if (message == "kick")
                    {
                        server.CloseConnection(clientID, true, 0);
                        continue;
                    }

                    if (message == "stat")
                    {
                        rss = server.GetStatistics(server.GetSystemAddressFromIndex(0));
                        RakNet.RakNet.StatisticsToString(rss, out message, 2);
                        Console.WriteLine(message);
                        continue;
                    }
                    if (message == "ping")
                    {
                        server.Ping(clientID);
                        continue;
                    }
                    if (message == "list")
                    {
                        SystemAddress[] systems = new SystemAddress[10];
                        ushort          numCons = 10;
                        server.GetConnectionList(out systems, ref numCons);
                        for (int i = 0; i < numCons; i++)
                        {
                            Console.WriteLine((i + 1).ToString() + ". " + systems[i].ToString(true));
                        }
                        continue;
                    }

                    if (message == "ban")
                    {
                        Console.WriteLine("'Enter IP to ban.  You can use * as a wildcard");
                        message = Console.ReadLine();
                        server.AddToBanList(message);
                        Console.WriteLine("IP " + message + " added to ban list.");
                        continue;
                    }

                    string message2;
                    message2 = "Server: " + message;
                    server.Send(message2, message2.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true);
                }

                for (p = server.Receive(); p != null; server.DeallocatePacket(p), p = server.Receive())
                {
                    packetIdentifier = GetPacketIdentifier(p);
                    switch ((DefaultMessageIDTypes)packetIdentifier)
                    {
                    case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                        Console.WriteLine("ID_DISCONNECTION_NOTIFICATION from " + p.systemAddress.ToString(true));
                        break;

                    case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION:
                        Console.WriteLine("ID_NEW_INCOMING_CONNECTION from " + p.systemAddress.ToString(true) + "with GUID " + p.guid.ToString());
                        clientID = p.systemAddress;
                        Console.WriteLine("Remote internal IDs: ");
                        for (int index = 0; index < MAXIMUM_NUMBER_OF_INTERNAL_IDS; index++)
                        {
                            SystemAddress internalId = server.GetInternalID(p.systemAddress, index);
                            if (internalId != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS)
                            {
                                Console.WriteLine((index + 1).ToString() + ". " + internalId.ToString(true));
                            }
                        }
                        break;

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

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

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

                    default:
                        Console.WriteLine(System.Text.Encoding.UTF8.GetString(p.data));
                        message = System.Text.Encoding.UTF8.GetString(p.data);
                        server.Send(message, message.Length + 1, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true);
                        break;
                    }
                }
            }
            server.Shutdown(300);
            RakNet.RakPeerInterface.DestroyInstance(server);
            Console.Read();
        }