private IConnection OnConnection(RakNet.Packet packet, RakPeerInterface server)
        {
            logger.Trace("Connected to endpoint {0}", packet.systemAddress);

            IConnection c   = CreateNewConnection(packet.guid, server);
            var         ctx = new PeerConnectedContext {
                Connection = c
            };
            var pconnected = _connectionHandler.PeerConnected;

            if (pconnected != null)
            {
                pconnected(ctx);
            }

            c = ctx.Connection;
            server.DeallocatePacket(packet);
            _handler.NewConnection(c);
            var action = ConnectionOpened;

            if (action != null)
            {
                action(c);
            }

            c.SendSystem((byte)MessageIDTypes.ID_CONNECTION_RESULT, s => s.Write(BitConverter.GetBytes(c.Id), 0, 8));
            return(c);
        }
        private void OnDisconnection(RakNet.Packet packet, RakPeerInterface server, string reason)
        {
            logger.Trace("Disconnected from endpoint {0}", packet.systemAddress);
            var c = RemoveConnection(packet.guid);

            server.DeallocatePacket(packet);

            _handler.CloseConnection(c, reason);

            var action = ConnectionClosed;

            if (action != null)
            {
                action(c);
            }

            if (c != null)
            {
                var a = c.ConnectionClosed;
                if (a != null)
                {
                    a(reason);
                }
            }
        }
示例#3
0
        private void OnMessageReceived(RakNet.Packet packet)
        {
            var connection = GetConnection(packet.guid);
            var buffer     = new byte[packet.data.Length];

            packet.data.CopyTo(buffer, 0);
            _peer.DeallocatePacket(packet);
            var p = new Stormancer.Core.Packet(
                connection,
                new MemoryStream(buffer));

            _logger.Trace("transports.raknet", "message with id {0} arrived", buffer[0]);

            this.PacketReceived(p);
        }
示例#4
0
        private void OnDisconnection(RakNet.Packet packet, RakPeerInterface server, string reason)
        {
            _logger.Trace("transports.raknet", "{0} disconnected", packet.systemAddress);

            var c = RemoveConnection(packet.guid);

            server.DeallocatePacket(packet);
            _handler.CloseConnection(c, reason);
            c.RaiseConnectionClosed(reason);

            var action = ConnectionClosed;

            if (action != null)
            {
                action(c);
            }
        }
        private void OnConnection(RakNet.Packet packet, RakPeerInterface server)
        {
            logger.Trace("Connected to endpoint {0}", packet.systemAddress);

            var c = CreateNewConnection(packet.guid, server);

            server.DeallocatePacket(packet);
            _handler.NewConnection(c);
            var action = ConnectionOpened;

            if (action != null)
            {
                action(c);
            }

            c.SendSystem((byte)MessageIDTypes.ID_CONNECTION_RESULT, s => s.Write(BitConverter.GetBytes(c.Id), 0, 8));
        }
示例#6
0
    public void Update()
    {
        if (this.server == null)
        {
            Debug.LogError("this.server = null");
            return;
        }

        Packet recvPkg = this.server.Receive();

        if (recvPkg == null)
        {
            return;
        }

        byte type = recvPkg.data[0];

        switch ((DefaultMessageIDTypes)type)
        {
        case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
        case DefaultMessageIDTypes.ID_CONNECTION_LOST:
        case DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION:
        case DefaultMessageIDTypes.ID_REMOTE_CONNECTION_LOST:
            Log.WriteLine("连接断开");
            break;

        case DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION:
            string str = string.Format("终端 {0} 连入", recvPkg.systemAddress.ToString(true));
            Log.WriteLine(str);
            break;

        // raknet自定义事件类型
        case DefaultMessageIDTypes.ID_USER_PACKET_ENUM:
        {
            // 回转
            RakNet.BitStream bs = new RakNet.BitStream();
            bs.Write(recvPkg.data, recvPkg.length);
            server.Send(bs, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, recvPkg.systemAddress, false);
        }
        break;
        }

        server.DeallocatePacket(recvPkg);
    }
        private void OnMessageReceived(RakNet.Packet packet)
        {
            //var messageId = packet.data[0];
            var connection = GetConnection(packet.guid);
            var stream     = new MemoryStream((int)packet.length);

            //var buffer = new byte[packet.data.Length];
            stream.Write(packet.data, 0, (int)packet.length);
            stream.Seek(0, SeekOrigin.Begin);
            _peer.DeallocatePacket(packet);
            //logger.Trace("message arrived: [{0}]", string.Join(", ", buffer.Select(b => b.ToString()).ToArray()));

            var p = new Stormancer.Core.Packet(
                connection,
                stream);


            this.PacketReceived(p);
        }
        private void OnMessageReceived(RakNet.Packet packet)
        {
            var messageId  = packet.data[0];
            var connection = GetConnection(packet.guid);
            var stream     = new MemoryStream((int)packet.length);

            //var buffer = new byte[packet.data.Length];
            stream.Write(packet.data, 0, (int)packet.length);
            stream.Seek(0, SeekOrigin.Begin);
            logger.Log(Stormancer.Diagnostics.LogLevel.Trace, "transport", "message received  at " + DateTime.Now + "." + DateTime.Now.Millisecond + ": " + string.Join(";", packet.data.Select(b => b.ToString()).ToArray()));
            _peer.DeallocatePacket(packet);
            //logger.Trace("message arrived: [{0}]", string.Join(", ", buffer.Select(b => b.ToString()).ToArray()));

            var p = new Stormancer.Core.Packet(
                connection,
                stream);


            this.PacketReceived(p);
        }
示例#9
0
        public void Update()
        {
            if (client == null)
            {
                return;
            }

            if (connectionView == null)
            {
                Process process = Process.ThisProcess();
                connectionView = zCView.Create(process, 0, 0, 0x2000, 0x2000);
                zString    str = zString.Create(process, "Connection aborted!");
                zCViewText vt  = connectionView.CreateText(0x950, 0x800, str);
                str.Dispose();
                vt.Color.G = 0;
                vt.Color.B = 0;
                vt.Color.R = 255;
                vt.Color.A = 255;

                vt.Timed = 0;
                vt.Timer = -1;
            }

            if (!shown && (client.GetLastPing(client.GetSystemAddressFromIndex(0)) > 1000 || client.GetLastPing(client.GetSystemAddressFromIndex(0)) <= -1))
            {
                zCView.GetStartscreen(Process.ThisProcess()).InsertItem(connectionView, 0);
                shown = true;
            }
            else if (shown && (client.GetLastPing(client.GetSystemAddressFromIndex(0)) < 700 && client.GetLastPing(client.GetSystemAddressFromIndex(0)) > -1))
            {
                zCView.GetStartscreen(Process.ThisProcess()).RemoveItem(connectionView);
                shown = false;
            }

            int    counter = 0;
            Packet packet  = client.Receive();


            while (packet != null)
            {
                WinApi.Kernel.Process.SetWindowText(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle, "Gothic II - Untold Chapters - " + client.GetLastPing(client.GetSystemAddressFromIndex(0)));

                switch (packet.data[0])
                {
                case (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                    isConnected    = true;
                    connectionTrys = 0;
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                    logError("Connection Failed!");
                    isConnected = false;
                    break;

                case (byte)DefaultMessageIDTypes.ID_ALREADY_CONNECTED:
                    logError("Already Connected!");
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_BANNED:
                    logError("Client banned!");
                    break;

                case (byte)DefaultMessageIDTypes.ID_INVALID_PASSWORD:
                    logError("Wrong password");
                    break;

                case (byte)DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                    logError("ID_INCOMPATIBLE_PROTOCOL_VERSION");
                    break;

                case (byte)DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:
                    logError("ID_NO_FREE_INCOMING_CONNECTIONS");
                    break;

                case (byte)DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                case (byte)DefaultMessageIDTypes.ID_CONNECTION_LOST:
                    isConnected = false;
                    break;

                case (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM:
                    try
                    {
                        receiveBitStream.Reset();
                        receiveBitStream.Write(packet.data, packet.length);
                        receiveBitStream.IgnoreBytes(2);
                        if ((Player.Hero == null || Player.Hero.ID == 0) && packet.data[1] != (byte)NetworkID.ConnectionMessage)
                        {
                            break;
                        }
                        if (messageListener.ContainsKey(packet.data[1]))
                        {
                            messageListener[packet.data[1]].Read(receiveBitStream, packet, this);
                        }
                    }
                    catch (Exception ex) { zERROR.GetZErr(Process.ThisProcess()).Report(2, 'G', ex.Message + ex.StackTrace, 0, "Client.cs", 0); }
                    break;
                }

                client.DeallocatePacket(packet);


                counter++;
                if (counter >= 1000)
                {
                    counter = 0;
                    zERROR.GetZErr(Process.ThisProcess()).Report(2, 'G', "1000 Packete hintereinander", 0, "Client.cs", 0);
                }

                packet = client.Receive();
            }
        }
示例#10
0
        public void Update(GameTime gameTime, ref Player player)
        {
            for (packet = peer.Receive(); packet != null; peer.DeallocatePacket(packet), packet = peer.Receive())
            {
                BitStream bsIn = new BitStream(packet.data, packet.length, false);
                bsIn.IgnoreBytes(1);
                switch (packet.data[0])
                {
                case (byte)GameMessages.REMOVE_DISCONNECTED_CLIENT:
                    /*   bsIn.Read(out removeID); // Receive the disconnected clients ID
                     * bsIn.Read(out removeAddress);
                     * foreach(otherClients dcClient in otherClientsList)
                     * {
                     *     if(dcClient.clientAddress == removeAddress)
                     *     {
                     *         otherClientsList.Remove(dcClient);
                     *         break;
                     *     }
                     * }*/
                    break;

                case (byte)GameMessages.SPAWN_POSITION:
                    bsIn.Read(out client_id);
                    bsIn.Read(out posX);     // Receive spawn location
                    bsIn.Read(out posY);     // Receive spawn
                    Console.WriteLine(posY);
                    // Repos of camera might be needed here aswell.
                    Console.WriteLine("We are Client Number: {0} at location: {1},{2}", int_message, posX, posY);
                    player.xPos    = posX;
                    player.yPos    = posY;
                    server_address = packet.systemAddress;
                    break;

                case (byte)GameMessages.WELCOME:
                    Console.WriteLine("Server said we are client number: " + int_message);
                    break;

                case (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED:
                    connected = true;
                    Console.WriteLine("Connection Accepted");
                    break;

                case (byte)GameMessages.POSITION_UPDATE:         // Receive positions
                    bsIn.Read(out other_client_id);
                    bsIn.Read(out other_client_x);
                    bsIn.Read(out other_client_y);
                    foreach (otherClients oClient in otherClientsList)
                    {
                        if (oClient.id == other_client_id && oClient.id != client_id)
                        {
                            oClient.xPos = other_client_x;
                            oClient.yPos = other_client_y;
                        }
                    }
                    Console.WriteLine("Received another clients position");
                    Console.WriteLine("Received another clients position");
                    break;

                case (byte)GameMessages.YOUR_TURN:
                    /*bsOut.Reset();
                     * Console.WriteLine("My turn, sending message.");
                     * bsOut.Write((byte)GameMessages.POSITION_UPDATE);  // Send position
                     * bsOut.Write(client_id);
                     * bsOut.Write(20); // Our X position
                     * bsOut.Write(20); // Our Y position
                     * Console.WriteLine("Position sent");
                     * peer.Send(bsOut, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, packet.systemAddress, false);
                     * bsOut.Reset(); */
                    break;

                case (byte)GameMessages.NEW_CLIENT:
                    // Receive given data./

                    /*
                     *      bsIn.Read(out other_client_id); // Receive the given ID
                     *      bsIn.Read(out other_client_x);
                     *      bsIn.Read(out other_client_y); */
                    // Do stuff with new client
                    bsIn.Read(out other_client_id);
                    bsIn.Read(out other_client_x);
                    bsIn.Read(out other_client_y);
                    otherClientsList.Add(new otherClients(other_client_id, other_client_x, other_client_y, other_address));
                    break;

                default:
                    Console.WriteLine("Message with identifier " + packet.data[0] + " has arrived.");
                    break;
                }
                bsOut.Reset();
            }
            //Code to send our position to the server.
            if (true)
            {
                Console.WriteLine("We (Client {0}) sent our position: {1},{2}", client_id, player.xPos, player.yPos);
                bsOut.Reset();
                bsOut.Write((byte)GameMessages.POSITION_UPDATE);
                bsOut.Write(client_id);
                bsOut.Write(player.xPos);
                bsOut.Write(player.yPos);
                peer.Send(bsOut, PacketPriority.HIGH_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, server_address, false);
            }
            Console.WriteLine("We are client {0}.", client_id);
        }
示例#11
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.");
    }
示例#12
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();
        }
示例#13
0
    void Update()
    {
        ++frameCount;
        if (client == null)
        {
            return;
        }

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

            case DefaultMessageIDTypes.ID_ALREADY_CONNECTED:
                Debug.Log("ID_ALREADY_CONNECTED with guid " + p.guid);
                break;

            case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                Debug.Log("ID_INCOMPATIBLE_PROTOCOL_VERSION ");
                break;

            case DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION:
                Debug.Log("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.
                Debug.Log("ID_REMOTE_CONNECTION_LOST");
                break;

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

            case DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED:
                Debug.Log("Connection attempt failed ");
                break;

            case DefaultMessageIDTypes.ID_NO_FREE_INCOMING_CONNECTIONS:
                Debug.Log("Server is full ");
                break;

            case DefaultMessageIDTypes.ID_INVALID_PASSWORD:
                Debug.Log("ID_INVALID_PASSWORD\n");
                break;

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

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

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

            default:
                messageCount++;
                System.DateTime now  = System.DateTime.Now;
                string          info = System.Text.Encoding.UTF8.GetString(p.data).Trim();
                try{
                    var data    = PacketDataDefine.FromJson(info);
                    int millsec = PacketDataDefine.TimeSpan(data);
                    int ping    = millsec;
                    if (data.Index != 1 + lastFrame)
                    {
                        ++errorCount;
                    }
                    lastFrame  = data.Index;
                    totalPing += ping;
                    //string[] t = info.Trim().Split();
                    //int serverToClientDuration = (now.Second - int.Parse(t[6])) * 1000 + (now.Millisecond - int.Parse(t[7]));
                    //int clientToServerDuration = (now.Second - int.Parse(t[2])) * 1000 + (now.Millisecond - int.Parse(t[3]));
                    //string outInfo = string.Format("{0}服务器到客户端:{1}ms  客户端到服务器:{2}ms", info, serverToClientDuration, clientToServerDuration);
                    string outInfo = string.Format("Index:{0} Ping:{1}ms Content{2}", data.Index, ping, data.Content);
                    PrintContent(outInfo);

                    statText.text = string.Format("平均Ping:{0}  消息总数:{1}  错误顺序:{2}", AveragePing, messageCount, errorCount - 1);
                }
                catch {
                    PrintContent(info);
                }
                break;
            }
        }

        if (bSendRandomPacket)
        {
            SendRandomPacket();
        }
        else
        {
            lastFrame = frameCount;
        }
    }
示例#14
0
    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;
            }
        }
    }
示例#15
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);
            }
        }
示例#16
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);
                }
            }
        }
示例#17
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();
        }
示例#18
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();
        }
示例#19
0
        private void Listening()
        {
            while (true)
            {
                Thread.Sleep(10);
                for (p = server.Receive(); p != null; server.DeallocatePacket(p), p = server.Receive())
                {
                    AddSenderInfo(string.Format("Time:{0} IP:{1} GUID:{2} Length:{3}", System.DateTime.Now.TimeOfDay, p.systemAddress.ToString(), p.guid, p.length));

                    packetIdentifier = GetPacketIdentifier(p);
                    switch ((DefaultMessageIDTypes)packetIdentifier)
                    {
                    case DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION:
                        MessageBox("ID_DISCONNECTION_NOTIFICATION");
                        break;

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

                    case DefaultMessageIDTypes.ID_INCOMPATIBLE_PROTOCOL_VERSION:
                        MessageBox("ID_INCOMPATIBLE_PROTOCOL_VERSION ");
                        break;

                    case DefaultMessageIDTypes.ID_REMOTE_DISCONNECTION_NOTIFICATION:
                        MessageBox("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.
                        MessageBox("ID_REMOTE_CONNECTION_LOST");
                        break;

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

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

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

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

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

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

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

                    default:
                        RakString s = new RakString();
                        s.AppendBytes(p.data, (uint)p.data.Length);
                        AddReceivedData(s.C_String());
                        BinaryData.Add(p.data);
                        break;
                    }
                }
            }
        }
示例#20
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;
        }
示例#21
0
        internal static void Update()
        {
            int            counter = 0;
            ServerMessages msgType;
            Packet         packet;

            // Receive packets
            while ((packet = clientInterface.Receive()) != null)
            {
                try
                {
                    receivedBytes += packet.length;

                    packetReader.Load(packet.data, (int)packet.length);
                    msgType = (ServerMessages)packetReader.ReadByte();
                    ReadMessage(msgType, packetReader);

                    counter++;
                    if (counter >= 1000)
                    {
                        counter = 0;
                        Logger.Log("1000 Pakete hintereinander");
                    }
                }
                catch (Exception e)
                {
                    if (packet.length >= 1)
                    {
                        Logger.LogError("{0}: {1}: {2}\n{3}", (ServerMessages)packet.data[0], e.Source, e.Message, e.StackTrace);
                    }
                    else
                    {
                        Logger.LogError("{0}: {1}\n{2}", e.Source, e.Message, e.StackTrace);
                    }
                }
                finally
                {
                    clientInterface.DeallocatePacket(packet);
                }
            }

            #region Debug Info

            // update only every second
            if (infoTimer.IsReady)
            {
                int ping = clientInterface.GetLastPing(clientInterface.GetSystemAddressFromIndex(0));

                if (isDisconnected)
                {
                    abortInfo.Texts[0].Text = "Verbindung geschlossen!";
                    abortInfo.Show();
                }
                else if (isConnected)
                {
                    if (ping > 300 || ping < 0)
                    {
                        abortInfo.Show();
                    }
                    else
                    {
                        abortInfo.Hide();
                    }
                }

                // update ping text on screen
                int           devIndex = 0;
                GUCVisualText pingText = devInfo.Texts[devIndex++];
                pingText.Text = string.Format("Ping: {0}ms", ping);
                ColorRGBA color;
                if (ping <= 120)
                {
                    color = new ColorRGBA((byte)(40 + 180 * ping / 120), 220, 40);
                }
                else if (ping <= 220)
                {
                    color = new ColorRGBA(220, (byte)(220 - 180 * (ping - 100) / 120), 40);
                }
                else
                {
                    color = new ColorRGBA(220, 40, 40);
                }
                pingText.SetColor(color);

                long          fps     = Hooks.hGame.LastElapsedTicks > 0 ? TimeSpan.TicksPerSecond / Hooks.hGame.LastElapsedTicks : 999;
                GUCVisualText fpsText = devInfo.Texts[devIndex++];
                fpsText.Text = "FPS: " + fps;
                if (fps < 10)
                {
                    color = new ColorRGBA(220, 40, 40);
                }
                else if (fps < 40)
                {
                    color = new ColorRGBA(220, (byte)(40 + 180 * (fps - 10) / 30), 40);
                }
                else if (fps < 90)
                {
                    color = new ColorRGBA((byte)(220 - 180 * (fps - 40) / 50), 220, 40);
                }
                else
                {
                    color = new ColorRGBA(40, 220, 40);
                }
                fpsText.SetColor(color);

                devInfo.Texts[devIndex++].Text = "Spike: " + Hooks.hGame.SpikeLongest / TimeSpan.TicksPerMillisecond + "ms";

                // update kB/s text on screen
                int kbs = (int)(receivedBytes);
                devInfo.Texts[devIndex++].Text = ("Net received: " + kbs + "B/s");
                kbs = (int)(sentBytes);
                devInfo.Texts[devIndex++].Text = ("Net Sent: " + kbs + "B/s");
                receivedBytes = 0;
                sentBytes     = 0;

                if (World.Current != null)
                {
                    devIndex = 8;
                    devInfo.Texts[devIndex++].Text = World.Current.VobCount + " Vobs";
                    devInfo.Texts[devIndex++].Text = Client.guidedIDs.Count + " guided";

                    devInfo.Texts[devIndex++].Text = "Weather: " + World.Current.WeatherCtrl.CurrentWeight + " " + World.Current.Clock.Time.ToString(false);
                    devInfo.Texts[devIndex++].Text = "Barrier: " + World.Current.BarrierCtrl.CurrentWeight + " " + World.Current.BarrierCtrl.EndWeight;

                    devInfo.Texts[devIndex++].Text = "VobSounds: " + SoundHandler.VobSoundCount;
                    devInfo.Texts[devIndex++].Text = "PosSounds: " + SoundHandler.PosSoundCount;

                    //if (NPC.Hero != null)
                    //    devInfo.Texts[devIndex++].Text =  NPC.Hero.Movement.ToString();
                }
            }

            #endregion
        }
示例#22
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();
        }