Exemple #1
0
    /// <summary>
    /// Call this method along with your game loop, if you don't do this, you won't be able to receive messages
    /// </summary>
    public void ServerUpdate()
    {
        if (IsActive())
        {
            while (peer.HasReceived(out BitStream bitStream, out ulong guid, out int packet_size))
            {
                DefaultMessageIDTypes packet_id = (DefaultMessageIDTypes)bitStream.ReadByte();

                if (packet_id < DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    switch (packet_id)
                    {
                    case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION:
                        OnConnected(guid);
                        break;

                    case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                        OnDisconnected(guid, DisconnectReason.ConnectionClosed);
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_LOST:
                        OnDisconnected(guid, DisconnectReason.ConnectionLost);
                        break;
                    }
                }
                else if (packet_id >= DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    bitStream.ResetReadPointer();
                    OnSerializeData(bitStream, guid, packet_size);
                }
            }
        }
    }
    IEnumerator waitForResponseFromServer2(RakNetGUID hostGUID, Action <int, int> onHolePunched2)
    {
        ushort natListenPort = 0, natConnectPort = 0;

        while (true)
        {
            Packet packet = rakPeer2.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();
                    Debug.Log("conport " + natConnectPort);
                    rakPeer2.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 = rakPeer2.GetExternalID(packet.systemAddress).GetPort();
                    Debug.Log("lisport " + natListenPort);
                    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
                    rakPeer2.Shutdown(0);

                    // Hole is punched!
                    onHolePunched2(natListenPort, natConnectPort);

                    //StartCoroutine(connectToNATFacilitator());

                    yield break;                     // Totally done

                default:
                    Debug.Log("RakNet Client received unexpected message type: " + ((DefaultMessageIDTypes)packet.data[0]).ToString());
                    break;
                }
            }
            yield return(new WaitForEndOfFrame());
        }
    }
Exemple #3
0
        public static void WriteMsgTypeError(this DefaultMessageIDTypes defaultMessageIDType, string errorMsg)
        {
            if (!canOutput)
            {
                return;
            }
            Console.ForegroundColor = ConsoleColor.Yellow;
            string msgStr = string.Format(@"{0} - {1}  {2}", defaultMessageIDType.GetMessageIDTypeStr(), errorMsg, DateTime.Now.GetDefaultFormat());

            Console.WriteLine(msgStr);
            Console.ResetColor();
            Debug.WriteLine(msgStr);
        }
Exemple #4
0
        public static void WriteMsgTypeInfo(this DefaultMessageIDTypes defaultMessageIDType, RakPeerInterface rakPeer, string address, ushort port, string msg)
        {
            if (!canOutput)
            {
                return;
            }
            Console.ForegroundColor = ConsoleColor.Green;
            string msgStr = string.Format(@"[{0}:{1}]-[{2}]-[{3}:{4}]-{5}:{6}",
                                          rakPeer.GetMyBoundAddress().ToString(false),
                                          rakPeer.GetMyBoundAddress().GetPort(),
                                          DateTime.Now.GetDefaultFormat(),
                                          address,
                                          port,
                                          defaultMessageIDType.GetMessageIDTypeStr(),
                                          msg);

            Console.WriteLine(msgStr);
            Console.ResetColor();
            Debug.WriteLine(msgStr);
        }
    IEnumerator waitForResponseFromServerTest(RakNetGUID hostGUID)
    {
        ushort natListenPort = 0, natConnectPort = 0;

        while (true)
        {
            Packet packet = rakPeerTest.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();
                    rakPeerTest.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 = rakPeerTest.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
                    rakPeerTest.Shutdown(0);
                    connectedToFacTest = false;
                    // Hole is punched!
                    onHolePunchedTest(natListenPort, natConnectPort);

                    //ConnectFacTest (); //reconnect for server
                    //StartCoroutine(connectToNATFacilitator());

                    yield break;                     // Totally done

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

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

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

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

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

                default:
                    Debug.Log("RakNet Client received unexpected message type: " + ((DefaultMessageIDTypes)packet.data[0]).ToString());
                    yield break;
                }
            }
            yield return(new WaitForEndOfFrame());
        }
    }
Exemple #6
0
 public static string GetMessageIDTypeStr(this DefaultMessageIDTypes defaultMessageIDType)
 {
     return(string.Format(@"[{0}-{1}]", (int)defaultMessageIDType, defaultMessageIDType.ToString()));
 }
Exemple #7
0
        public void ProcessMessage()
        {
            while (!_bStop)
            {
                _packet = _peer.Receive();
                while (_packet != null)
                {
                    byte messageType = _packet.data[0];
                    if (messageType < (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                    {
                        DefaultMessageIDTypes idType = (DefaultMessageIDTypes)messageType;
                        switch (idType)
                        {
                        case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                            Log.Info("In a client/server environment, our connection request to the server has been accepted.\n");
                            break;

                        case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                            Log.Info("Sent to the player when a connection request cannot be completed due to inability to connect.\n ");
                            break;

                        case DefaultMessageIDTypes.ID_ALREADY_CONNECTED:
                            Log.Info("Sent a connect request to a system we are currently connected to.\n ");
                            break;

                        case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION:
                            Log.Info("A remote system has successfully connected.\n");
                            break;

                        case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                            Log.Info(" A remote system has disconnected. \n");
                            break;

                        case DefaultMessageIDTypes.ID_CONNECTION_LOST:
                            Log.Info(" The connection to that system has been closed. \n");
                            break;
                        }
                    }
                    else
                    {
                        if (messageType == (byte)FT_MessageTypes.ID_SERVER_LOGIN)
                        {
                            byte             dataType = _packet.data[1];
                            RakNet.BitStream bsIn     = new RakNet.BitStream(_packet.data, _packet.length, false);
                            bsIn.IgnoreBytes(2);
                            FT_UnitData unitData = new FT_UnitData();
                            unitData.session.Serialize(false, bsIn);
                            unitData.Serialize(false, bsIn);
                            Log.Info("" + unitData.sInfo.C_String());

                            byte serverLogin = (byte)RakNet.FT_MessageTypes.ID_SERVER_LOGIN;

                            RakNet.BitStream bsOut = new RakNet.BitStream();
                            bsOut.Serialize(true, ref serverLogin);
                            bsOut.Serialize(true, ref dataType);
                            unitData.session.Serialize(true, bsOut);
                            unitData.Serialize(true, bsOut);

                            uint sendLength = _peer.Send(bsOut,
                                                         RakNet.PacketPriority.IMMEDIATE_PRIORITY,
                                                         RakNet.PacketReliability.RELIABLE_ORDERED, (char)0,
                                                         _packet.systemAddress,
                                                         false);

                            Log.Info("SendLength:" + sendLength);
                        }
                    }
                    Log.Info(string.Format("Receive Data. [0] = {0}, Length = {1}", _packet.data[0], _packet.data.Length));
                    _peer.DeallocatePacket(_packet);
                    _packet = _peer.Receive();
                }
                System.Threading.Thread.Sleep(30);
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            int              BIG_PACKET_SIZE = 103296250;
            bool             quit;
            bool             sentPacket = false;
            RakPeerInterface client, server;

            byte[] text;
            string message;

            client = server = null;
            string ip = string.Empty;

            text = new byte[BIG_PACKET_SIZE];
            quit = false;
            char ch;

            Console.WriteLine("Enter 's' to run as server, 'c' to run as client, space to run local.");
            ch      = ' ';
            message = Console.ReadLine();

            ch = message.ToCharArray()[0];

            if (ch == 'c')
            {
                client = RakPeerInterface.GetInstance();
                Console.WriteLine("Working as client");
                Console.WriteLine("Enter remote IP: ");
                ip = Console.ReadLine();
                if (ip.Length == 0)
                {
                    ip = "127.0.0.1";
                }
            }
            else if (ch == 's')
            {
                server = RakPeerInterface.GetInstance();
                Console.WriteLine("Working as server");
            }
            else
            {
                client = RakPeerInterface.GetInstance();
                server = RakPeerInterface.GetInstance();
                ip     = "127.0.0.1";
            }

            short socketFamily;

            socketFamily = AF_INET;
            if (server != null)
            {
                server.SetTimeoutTime(5000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS);
                SocketDescriptor socketDescriptor = new SocketDescriptor(3000, "0");
                socketDescriptor.socketFamily = socketFamily;
                server.SetMaximumIncomingConnections(4);
                StartupResult sr = new StartupResult();
                sr = server.Startup(4, socketDescriptor, 1);
                if (sr != StartupResult.RAKNET_STARTED)
                {
                    Console.WriteLine("Error: Server failed to start: {0} ", sr.ToString());
                    return;
                }

                // server.SetPerConnectionOutgoingBandwidthLimit(50000);
                Console.WriteLine("Server started on {0}", server.GetMyBoundAddress().ToString());
            }

            if (client != null)
            {
                client.SetTimeoutTime(5000, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS);
                SocketDescriptor socketDescriptor = new SocketDescriptor(0, "0");
                socketDescriptor.socketFamily = socketFamily;
                client.SetMaximumIncomingConnections(4);
                StartupResult sr = new StartupResult();
                sr = client.Startup(4, socketDescriptor, 1);
                if (sr != StartupResult.RAKNET_STARTED)
                {
                    Console.WriteLine("Error: Server failed to start: " + sr.ToString());
                    return;
                }
                client.SetSplitMessageProgressInterval(10000); // Get ID_DOWNLOAD_PROGRESS notifications

                client.SetPerConnectionOutgoingBandwidthLimit(10000);
                Console.WriteLine("Client started on {0}", client.GetMyBoundAddress().ToString());
                client.Connect(ip, 3000, null, 0);
            }

            System.Threading.Thread.Sleep(500);

            Console.WriteLine("My IP addresses: ");
            RakPeerInterface rakPeer;

            if (server != null)
            {
                rakPeer = server;
            }
            else
            {
                rakPeer = client;
            }

            for (uint i = 0; i < rakPeer.GetNumberOfAddresses(); i++)
            {
                Console.WriteLine("{0}. {1}", (i + 1).ToString(), rakPeer.GetLocalIP(i).ToString());
            }

            uint start, stop = 0;

            uint   nextStatTime = RakNet.RakNet.GetTimeMS() + 1000;
            Packet packet = new Packet();

            start = RakNet.RakNet.GetTimeMS();
            while (!quit)
            {
                if (server != null)
                {
                    for (packet = server.Receive(); packet != null; server.DeallocatePacket(packet), packet = server.Receive())
                    {
                        if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION || packet.data[0] == (int)253)
                        {
                            Console.WriteLine("Starting send");
                            start = RakNet.RakNet.GetTimeMS();
                            if (BIG_PACKET_SIZE < 100000)
                            {
                                for (int i = 0; i < BIG_PACKET_SIZE; i++)
                                {
                                    text[i] = (byte)(255 - (i & 255));
                                }
                            }
                            else
                            {
                                text[0] = (byte)255;
                            }
                            DefaultMessageIDTypes idtype = (DefaultMessageIDTypes)packet.data[0];
                            if (idtype == DefaultMessageIDTypes.ID_CONNECTION_LOST)
                            {
                                Console.WriteLine("ID_CONNECTION_LOST from {0}", packet.systemAddress.ToString());
                            }
                            else if (idtype == DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION)
                            {
                                Console.WriteLine("ID_DISCONNECTION_NOTIFICATION from {0}", packet.systemAddress.ToString());
                            }
                            else if (idtype == DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION)
                            {
                                Console.WriteLine("ID_NEW_INCOMING_CONNECTION from {0}", packet.systemAddress.ToString());
                            }
                            else if (idtype == DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED)
                            {
                                Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED from {0}", packet.systemAddress.ToString());
                            }

                            server.Send(text, BIG_PACKET_SIZE, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED_WITH_ACK_RECEIPT, (char)0, packet.systemAddress, false);
                        }
                    }
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo key = Console.ReadKey();
                        switch (key.Key)
                        {
                        case ConsoleKey.Spacebar:
                            Console.WriteLine("Sending medium priority message");
                            byte[] t = new byte[1];
                            t[0] = 254;
                            server.Send(t, 1, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)1, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true);
                            break;

                        case ConsoleKey.Q:
                            quit = true;
                            break;

                        default:
                            break;
                        }
                    }
                }
                if (client != null)
                {
                    packet = client.Receive();
                    while (packet != null)
                    {
                        DefaultMessageIDTypes idtype = (DefaultMessageIDTypes)packet.data[0];

                        if (idtype == DefaultMessageIDTypes.ID_DOWNLOAD_PROGRESS)
                        {
                            BitStream progressBS = new BitStream(packet.data, packet.length, false);
                            progressBS.IgnoreBits(8);
                            byte[] progress = new byte[4], total = new byte[4], partlength = new byte[4];

                            progressBS.ReadBits(progress, sizeof(uint) << 3, true);
                            progressBS.ReadBits(total, sizeof(uint) << 3, true);
                            progressBS.ReadBits(partlength, sizeof(uint) << 3, true);

                            Console.WriteLine("Progress: msgID= {0}, Progress: {1} / {2}, Partsize: {3}", packet.data[0].ToString(),
                                              BitConverter.ToUInt32(progress, 0).ToString(),
                                              BitConverter.ToUInt32(total, 0).ToString(),
                                              BitConverter.ToUInt32(partlength, 0).ToString());
                        }
                        else if (packet.data[0] == 255)
                        {
                            if (packet.length != BIG_PACKET_SIZE)
                            {
                                Console.WriteLine("Test failed. {0} bytes (wrong number of bytes.", packet.length);
                                quit = true;
                                break;
                            }

                            if (BIG_PACKET_SIZE <= 100000)
                            {
                                for (int i = 0; i < BIG_PACKET_SIZE; i++)
                                {
                                    if (packet.data[i] != 255 - (i & 255))
                                    {
                                        Console.WriteLine("Test failed. {0} bytes (bad data).", packet.length);
                                        quit = true;
                                        break;
                                    }
                                }
                            }

                            if (quit == false)
                            {
                                Console.WriteLine("Test Succeeded. {0} bytes.", packet.length);
                                bool repeat = false;
                                if (repeat)
                                {
                                    Console.WriteLine("Rerequesting send.");
                                    byte[] ch2 = new byte[1];
                                    ch2[0] = (byte)253;
                                    client.Send(ch2, 1, PacketPriority.MEDIUM_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)1, RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS, true);
                                    GC.Collect();
                                }
                                else
                                {
                                    quit = true;
                                    break;
                                }
                            }
                        }
                        else if ((int)packet.data[0] == 254)
                        {
                            Console.WriteLine("Got high priority message.");
                        }
                        else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_CONNECTION_LOST)
                        {
                            Console.WriteLine("ID_CONNECTION_LOST from {0}", packet.systemAddress.ToString());
                        }
                        else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION)
                        {
                            Console.WriteLine("ID_NEW_INCOMING_CONNECTION from {0}", packet.systemAddress.ToString());
                        }
                        else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED)
                        {
                            start = RakNet.RakNet.GetTimeMS();
                            Console.WriteLine("ID_CONNECTION_REQUEST_ACCEPTED from {0}", packet.systemAddress.ToString());
                        }
                        else if ((DefaultMessageIDTypes)packet.data[0] == DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED)
                        {
                            Console.WriteLine("ID_CONNECTION_ATTEMPT_FAILED from {0}", packet.systemAddress.ToString());
                        }

                        client.DeallocatePacket(packet);
                        packet = client.Receive();
                    }
                }
                uint currenttime = RakNet.RakNet.GetTimeMS();
                if (currenttime > nextStatTime)
                {
                    nextStatTime = RakNet.RakNet.GetTimeMS() + 1000;
                    RakNetStatistics rssSender   = new RakNetStatistics();
                    RakNetStatistics rssReceiver = new RakNetStatistics();
                    string           StatText;

                    if (server != null)
                    {
                        ushort i;
                        ushort numSystems = 1;
                        server.GetConnectionList(null, ref numSystems);
                        if (numSystems > 0)
                        {
                            for (i = 0; i < numSystems; i++)
                            {
                                server.GetStatistics(server.GetSystemAddressFromIndex(i), rssSender);
                                RakNet.RakNet.StatisticsToString(rssSender, out StatText, 2);
                                Console.WriteLine("==== System {0} ====", (i + 1).ToString());
                                Console.WriteLine("{0}", StatText);
                            }
                        }
                    }
                    if (client != null && server == null && client.GetGUIDFromIndex(0) != RakNet.RakNet.UNASSIGNED_RAKNET_GUID)
                    {
                        client.GetStatistics(client.GetSystemAddressFromIndex(0), rssReceiver);
                        RakNet.RakNet.StatisticsToString(rssReceiver, out StatText, 2);
                        Console.WriteLine("{0}", StatText);
                    }
                }
                System.Threading.Thread.Sleep(100);
            }
            string StatTextEnd = "";

            stop = RakNet.RakNet.GetTimeMS();
            double seconds = (double)(stop - start) / 1000.0;

            if (server != null)
            {
                RakNetStatistics rssSender2 = server.GetStatistics(server.GetSystemAddressFromIndex(0));
                RakNet.RakNet.StatisticsToString(rssSender2, out StatTextEnd, 2);
                Console.WriteLine("{0}", StatTextEnd);
            }
            Console.WriteLine("{0} bytes per second ({1} seconds). Press enter to quit", (int)((double)(BIG_PACKET_SIZE) / seconds), seconds);
            RakPeerInterface.DestroyInstance(server);
            RakPeerInterface.DestroyInstance(client);
            Console.Read();
        }
    /// <summary>
    /// Call this method along with your game loop, if you don't do this, you won't be able to receive messages
    /// </summary>
    public void ClientUpdate()
    {
        if (IsActive())
        {
            while (peer.HasReceived(out BitStream bitStream, out ulong guid, out int packet_size))
            {
                DefaultMessageIDTypes packet_id = (DefaultMessageIDTypes)bitStream.ReadByte();

                if (packet_id < DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    switch (packet_id)
                    {
                    case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                        IsConnecting = false;
                        IsConnected  = true;
                        ClientGUID   = peer.GetMyGUID();
                        ServerGUID   = guid;
                        OnConnected();
                        break;

                    case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.ConnectionClosed);
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_LOST:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.ConnectionLost);
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_BANNED:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.IsBanned);
                        break;

                    case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.IncompatibleProtocol);
                        break;

                    case DefaultMessageIDTypes.ID_INVALID_PASSWORD:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.InvalidPassword);
                        break;

                    case DefaultMessageIDTypes.ID_PUBLIC_KEY_MISMATCH:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.SecurityError);
                        break;

                    case DefaultMessageIDTypes.ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.SecurityError);
                        break;

                    case DefaultMessageIDTypes.ID_OUR_SYSTEM_REQUIRES_SECURITY:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.SecurityError);
                        break;

                    case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.AttemptFailed);
                        break;

                    case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.ServerIsFull);
                        break;

                    case DefaultMessageIDTypes.ID_IP_RECENTLY_CONNECTED:
                        IsConnecting = IsConnected = false;
                        peer.Shutdown();
                        OnDisconnected(DisconnectReason.ConnectionRecently);
                        break;

                    case DefaultMessageIDTypes.ID_UNCONNECTED_PONG:
                        bitStream.ResetReadPointer();
                        OnSerializeData(bitStream, packet_size);
                        break;
                    }
                }
                else if (packet_id >= DefaultMessageIDTypes.ID_USER_PACKET_ENUM)
                {
                    bitStream.ResetReadPointer();
                    OnSerializeData(bitStream, packet_size);
                }
            }
        }
    }
Exemple #10
0
        private void Run()
        {
            isThreadRunning = true;

            string peerAddress = "";
            ushort peerPort    = 0;
            Packet testPacket  = null;

            while (true)
            {
                Thread.Sleep(1);
                if (!isThreadRunning)
                {
                    break;
                }
                if (rakPeer == null)
                {
                    continue;
                }
                using (testPacket = rakPeer.Receive())
                {
                    if (testPacket == null || testPacket.data.Count() <= 0)
                    {
                        continue;
                    }
                    DefaultMessageIDTypes defaultMessageIDType = (DefaultMessageIDTypes)testPacket.data[0];
                    peerAddress = testPacket.systemAddress.ToString(false);
                    peerPort    = testPacket.systemAddress.GetPort();
                    switch (defaultMessageIDType)
                    {
                    case DefaultMessageIDTypes.ID_UNCONNECTED_PING:                             //1
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, " [ OnUnconnectedPing ]");
                        OnUnconnectedPing(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_UNCONNECTED_PING_OPEN_CONNECTIONS:                             //2
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, " [ OnUnconnectedPingOpenConnections ]");
                        OnUnconnectedPingOpenConnections(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_UNCONNECTED_PONG:                             //28
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, " [ OnUnconnectedPong ]");
                        OnUnconnectedPong(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_UDP_PROXY_GENERAL:                             //92  ID_UDP_PROXY_GENERAL类型
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "ID_UDP_PROXY_GENERAL类型 [ OnUdpProxyGeneral ]");
                        OnUdpProxyGeneral(peerAddress, peerPort, testPacket.data[1]);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_NAT_TYPE_DETECTION_REQUEST:                             //96 得到路由类型结果
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "得到路由类型结果 [ OnNatTypeDetectionRequest ]");
                        OnNatTypeDetectionRequest(peerAddress, peerPort, testPacket.data[1]);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_FCM2_NEW_HOST:                             //82
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, " [ OnFcm2NewHost ]");
                        OnFcm2NewHost(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:                             //25 - 协议版本不兼容,一般是由于两端AttachPlugin没有对应
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "协议版本不兼容,一般是由于两端AttachPlugin没有对应 [ OnIncompatibleProtocolVersion ]");
                        OnIncompatibleProtocolVersion(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_NAT_TARGET_NOT_CONNECTED:                            //62-客户端:客户端NAT穿透失败
                    case DefaultMessageIDTypes.ID_NAT_TARGET_UNRESPONSIVE:                             //63-客户端:客户端NAT穿透失败
                    case DefaultMessageIDTypes.ID_NAT_CONNECTION_TO_TARGET_LOST:                       //64-客户端:客户端NAT穿透失败
                    case DefaultMessageIDTypes.ID_NAT_ALREADY_IN_PROGRESS:                             //65-客户端:客户端NAT穿透失败
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "客户端NAT穿透失败 [ OnConnectionAttemptFailedCommon ]");
                        OnConnectionAttemptFailedCommon(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_NAT_PUNCHTHROUGH_FAILED:                             //66-客户端NAT穿透失败
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "客户端NAT穿透失败 [ OnNatPunchthroughFailed ]");
                        OnNatPunchthroughFailed(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_NAT_PUNCHTHROUGH_SUCCEEDED:                             //67-客户端NAT穿透成功
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "客户端NAT穿透成功 [ OnNatPunchthroughSucceeded ]");
                        OnNatPunchthroughSucceeded(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:                             //16-客户端:连接请求被接受
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "连接请求被接受 [ OnConnectionRequestAccepted ]");
                        OnConnectionRequestAccepted(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:                             //17-连接尝试失败
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "连接尝试失败 [ OnConnectionAttemptFailed ]");
                        OnConnectionAttemptFailed(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION:                             //19-服务器中有新连接进来
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "服务器中有新连接进来 [ OnNewIncomingConnection ]");
                        OnNewIncomingConnection(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:                             //20-没有可用的连接,服务器已经达到最大连接数
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "没有可用的连接,服务器已经达到最大连接数 [ OnNoFreeIncomingConnections ]");
                        OnNoFreeIncomingConnections(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:                             //21-客户端主动断开连接的通知
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "客户端主动断开连接的通知 [ OnDisconnectionNotification ]");
                        OnDisconnectionNotification(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_CONNECTION_LOST:                             //22-失去客户端连接
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "失去客户端连接 [ OnConnectionLost ]");
                        OnConnectionLost(peerAddress, peerPort);
                    }
                    break;

                    case DefaultMessageIDTypes.ID_USER_PACKET_ENUM:                             //134-接收消息
                    {
                        defaultMessageIDType.WriteMsgTypeInfo(rakPeer, peerAddress, peerPort, "接收消息 [ OnReiceve ]");
                        if (testPacket.data.Count() > 1)                                         //过滤掉通过proxy发送过来的用来保持连接的消息
                        {
                            OnRaknetReceive(peerAddress, peerPort, testPacket.data.Skip(1).ToArray());
                        }
                    }
                    break;

                    default:                             //消息标志异常,如果有需要,再另加case处理
                    {
                        defaultMessageIDType.WriteMsgTypeError(string.Format(@"[{0}:{1}] [{2}:{3}] 消息标志异常", rakPeer.GetMyBoundAddress().ToString(false), rakPeer.GetMyBoundAddress().GetPort(), peerAddress, peerPort));
                    }
                    break;
                    }
                }
            }
        }
    public void Update()
    {
        if (null == m_Socket)
        {
            return;
        }
        for (m_MessagePacket = m_Socket.Receive(); null != m_MessagePacket; m_Socket.DeallocatePacket(m_MessagePacket), m_MessagePacket = m_Socket.Receive())
        {
            // We got a packet, get the identifier with our handy function
            DefaultMessageIDTypes packetIdentifier = (DefaultMessageIDTypes)GetPacketIdentifier(m_MessagePacket);

            // Check if this is a network message packet
            switch (packetIdentifier)
            {
            case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                // Connection lost normally
                //printf("ID_DISCONNECTION_NOTIFICATION\n");
                OnDisconnected();
                break;

            case DefaultMessageIDTypes.ID_ALREADY_CONNECTED:
                // Connection lost normally
                //printf("ID_ALREADY_CONNECTED with guid %" PRINTF_64_BIT_MODIFIER "u\n", m_MessagePacket->guid);
                break;

            case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                //printf("ID_INCOMPATIBLE_PROTOCOL_VERSION\n");
                break;

            case DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION:     // Server telling the clients of another client disconnecting gracefully.  You can manually broadcast this in a peer to peer enviroment if you want.
                //printf("ID_REMOTE_DISCONNECTION_NOTIFICATION\n");
                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.
                //printf("ID_REMOTE_CONNECTION_LOST\n");
                OnDisconnected();
                break;

            case DefaultMessageIDTypes.ID_REMOTE_NEW_INCOMING_CONNECTION:     // Server telling the clients of another client connecting.  You can manually broadcast this in a peer to peer enviroment if you want.
                //printf("ID_REMOTE_NEW_INCOMING_CONNECTION\n");
                break;

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

            case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                //printf("Connection attempt failed\n");
                OnDisconnected();
                break;

            case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:
                // Sorry, the server is full.  I don't do anything here but
                // A real app should tell the user
                //printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
                OnDisconnected();
                break;

            case DefaultMessageIDTypes.ID_INVALID_PASSWORD:
                //printf("ID_INVALID_PASSWORD\n");
                OnDisconnected();
                break;

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

            case DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                // This tells the client they have connected
                //printf("ID_CONNECTION_REQUEST_ACCEPTED to %s with GUID %s\n", m_MessagePacket->systemAddress.ToString(true), m_MessagePacket->guid.ToString());
                //printf("My external address is %s\n", m_Socket->GetExternalID(m_MessagePacket->systemAddress).ToString(true));
                m_SystemAddress = m_MessagePacket.systemAddress;
                OnConnected();
                break;

            case DefaultMessageIDTypes.ID_CONNECTED_PING:
            case DefaultMessageIDTypes.ID_UNCONNECTED_PING:
                //printf("Ping from %s\n", m_MessagePacket->systemAddress.ToString(true));
                break;

            default:
                // It's a client, so just show the message
                //printf("%s\n", p->data);
                if (null != m_Stream)
                {
                    m_Stream.OnParseMessage();
                }
                break;
            }
        }
    }
Exemple #12
0
        /// <summary>
        /// 处理接受消息
        /// </summary>
        void ReceiveMessage()
        {
            receiveCount = 0;
            // 单帧处理消息数量不大于指定的消息数量
            while (receiveCount < MaxReceiveCount || !ProcUserMessage)
            {
                Packet packet = mClient.Receive();
                if (packet == null) // 没有消息内容了,不用解析,退出循环
                {
                    break;
                }
                receiveCount++;
                DefaultMessageIDTypes messageIDType = (DefaultMessageIDTypes)packet.data[0];
                LogMessage(messageIDType.ToString());
                switch (packet.data[0])
                {
                case (byte)DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                    //DisConnect();
                    EventDispatcher.Instance.TriggerEvent("Application_ConnectionLost", packet.data[0]);
                    break;

                case (byte)DefaultMessageIDTypes.ID_ALREADY_CONNECTED:
                    //Debug.Log("收到18消息");
                    DisConnect();
                    EventDispatcher.Instance.TriggerEvent("Application_ConnectionLost", packet.data[0]);
                    break;

                case (byte)DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                    break;

                case (byte)DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION:     // Server telling the clients of another m_Client disconnecting gracefully.  You can manually broadcast this in a peer to peer enviroment if you want.
                    break;

                case (byte)DefaultMessageIDTypes.ID_REMOTE_CONNECTION_LOST:     // Server telling the clients of another m_Client disconnecting forcefully.  You can manually broadcast this in a peer to peer enviroment if you want.
                    DisConnect();
                    EventDispatcher.Instance.TriggerEvent("Application_ConnectionLost", packet.data[0]);
                    break;

                case (byte)DefaultMessageIDTypes.ID_REMOTE_NEW_INCOMING_CONNECTION:     // Server telling the clients of another m_Client connecting.  You can manually broadcast this in a peer to peer enviroment if you want.
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_BANNED:     // Banned from this server
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                    DisConnect();
                    //ShutDown();
                    EventDispatcher.Instance.TriggerEvent("Application_ConnectionLost", packet.data[0]);
                    break;

                case (byte)DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:    // 服务器满员了
                    DisConnect();
                    EventDispatcher.Instance.TriggerEvent("Application_ConnectionLost", packet.data[0]);
                    // Sorry, the server is full.  I don't do anything here but
                    // A real app should tell the user
                    break;

                case (byte)DefaultMessageIDTypes.ID_INVALID_PASSWORD:    // 无效的密码
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_LOST:
                    // Couldn't deliver a reliable packet - i.e. the other system was abnormally
                    // terminated
                    DisConnect();
                    EventDispatcher.Instance.TriggerEvent("Application_ConnectionLost", packet.data[0]);
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:     // 连接成功
                {
                    IsConnectedServer = true;
                    //LogMessage(string.Format("ID_CONNECTION_REQUEST_ACCEPTED to {0} with GUID {1}", packet.systemAddress.ToString(true), packet.guid.ToString()));
                    //LogMessage(string.Format("My external address is {0}", mClient.GetExternalID(packet.systemAddress).ToString(true)));
                    m_serverAddress = packet.systemAddress;
                    m_guid          = packet.guid;
                    Debug.LogFormat("RakNetGUID:{0}", m_guid);
                    mClient.SetTimeoutTime(9000, m_serverAddress);
                    NotifyConnectCallBack(true);
                    break;
                }

                case (byte)DefaultMessageIDTypes.ID_CONNECTED_PING:
                case (byte)DefaultMessageIDTypes.ID_UNCONNECTED_PING:
                    LogMessage(string.Format("Ping from {0}", packet.systemAddress.ToString(true)));
                    break;

                case (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM:
                case (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM2:
                    if (ProcUserMessage == true)
                    {
                        Dispatch(packet);
                    }
                    break;

                default:
                    // It's a m_Client, so just show the message
                    LogMessage("Message ID Type default: " + packet.data[0]);
                    break;
                }
                mClient.DeallocatePacket(packet);
            }

            if (ProcUserMessage == false)
            {
                ProcUserMessage = true;
                // 抛出消息清除完毕的事件
                //Debug.Log("c#清空消息完毕");
                EventDispatcher.Instance.TriggerEvent("Application_ClearMessage_OK", null);
            }
        }