// send message button fucntionality
        private void SendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SendButton.IsEnabled = false;
                ClientFileManager fileManager = new ClientFileManager();
                //////// Implementing code for sending DLL's to repository before sending the test request.

                fileManager.client_Manager("client1");

                // creating messages to send to Test Harness Server
                Messages msg = makeMessage("nik", endPoint, endPoint);
                string   TestHarnessEndPoint = Comm <MainWindow> .makeEndPoint("http://localhost", 8080);

                msg.toUrl           = TestHarnessEndPoint;
                msg.command         = "TestRequest";
                msg.message_content = ClientMessages.makeTestRequestClient1();
                listBox1.Items.Insert(0, msg);
                if (listBox1.Items.Count > MaxMsgCount)
                {
                    listBox1.Items.RemoveAt(listBox1.Items.Count - 1);
                }
                comm.sndr.PostMessage(msg);
            }
            catch (Exception ex)
            {
                Window temp = new Window();
                temp.Content = ex.Message;
                temp.Height  = 100;
                temp.Width   = 500;
            }
        }
Ejemplo n.º 2
0
 protected virtual void gameDisconnected(ClientMessages msg, string reason)
 {
     connected = false;
     if (Disconnected != null)
     {
         Disconnected(msg, reason);
     }
 }
Ejemplo n.º 3
0
 public void DisconnectPlayer(Player player, ClientMessages reason = ClientMessages.Disconnected, string message = null)
 {
     using (var ms = new MemoryStream())
         using (var w = new BinaryWriter(ms))
         {
             DisconnectPlayer(w, player, reason, message);
             Send(ms, player.Address);
         }
 }
Ejemplo n.º 4
0
 public WsClientTestWrapper(WsHubClientOptions options)
 {
     Options    = options;
     Connection = new WsHubConnection(options);
     Connection.WebSocketConnected.Subscribe(ConnectionStatuses.Add);
     Connection.MessageHandler = msg =>
     {
         ClientMessages.Add(msg);
         return(Task.CompletedTask);
     };
 }
Ejemplo n.º 5
0
        internal RecordedEvent(ClientMessages.StreamEventAppeared streamEvent)
        {
            EventStreamId = streamEvent.EventStreamId;

            EventId = streamEvent.EventId;
            EventNumber = streamEvent.EventNumber;

            EventType = streamEvent.EventType;

            Data = streamEvent.Data;
            Metadata = streamEvent.Metadata;
        }
Ejemplo n.º 6
0
        protected virtual void OnPlayerDisconnected(Player p, ClientMessages reason)
        {
            using (var ms = new MemoryStream())
                using (var w = new BinaryWriter(ms))
                {
                    w.Write((byte)ClientMessages.OtherPlayerLeft);
                    w.Write(p.thePlayerName);

                    SendToAllPlayers(ms.ToArray());
                    CheckGameStartable();
                }
        }
Ejemplo n.º 7
0
            /// <summary>
            /// The send message.
            /// </summary>
            /// <param name="clientMessage">
            /// The client message.
            /// </param>
            /// <param name="data">
            /// The data.
            /// </param>
            private void SendMessage(ClientMessages clientMessage, Bundle data)
            {
                Message m = Message.Obtain(null, (int)clientMessage);

                m.Data = data;
                try
                {
                    this.serviceMessenger.Send(m);
                }
                catch (RemoteException e)
                {
                    e.PrintStackTrace();
                }
            }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            // Test Stub
            "XML Parser STUB ====>>>>>>>>> ".title('=');
            XMLParser xmlParser       = new XMLParser();
            string    message_content = ClientMessages.makeTestRequest();
            Queue <KeyValuePair <string, string> > xml_Info_queue = new Queue <KeyValuePair <string, string> >();

            xml_Info_queue = xmlParser.Parse(message_content);
            Console.WriteLine("Parsed Message: \n");
            foreach (KeyValuePair <string, string> x in xml_Info_queue)
            {
                Console.WriteLine("{0} -- {1}", x.Key, x.Value);
            }


            Console.ReadKey();
        }
Ejemplo n.º 9
0
 public void DisconnectPlayer(BinaryWriter w, Player player, ClientMessages reason = ClientMessages.Disconnected, string message = null, IPEndPoint ep = null)
 {
     OnPlayerDisconnecting(player, reason);
     lock (players)
         players.Remove(player);
     w.Write(player.ID);
     w.Write((byte)reason);
     if (message == null)
     {
         w.Write((byte)0);
     }
     else
     {
         w.Write(message);
     }
     if (ep != null)
     {
         player.Address = ep;
     }
     OnPlayerDisconnected(player, reason);
 }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            try
            {
                Console.Write("\n CLIENT2");
                Console.Write("\n =====================\n");

                Client2 client2 = new Client2();

                ClientFileManager fileManager = new ClientFileManager();
                //////// Implementing code for sending DLL's to repository before sending the test request.

                fileManager.client_Manager("client2");

                // creating messages to send to Test Harness Server
                Messages msg = client2.makeMessage("Ashu", client2.endPoint, client2.endPoint);
                string   TestHarnessEndPoint = Comm <Client2> .makeEndPoint("http://localhost", 8080);

                msg.toUrl           = TestHarnessEndPoint;
                msg.command         = "TestRequest";
                msg.message_content = ClientMessages.makeTestRequestClient2();
                " [[ Displaying Requirement 2 and 6 (Test Request)---->>> XML Body sent as a part of Request and specifies DLL's to execute  ]]".title('=');
                msg.show();
                Console.WriteLine("----------------------------------------------------------------------------------");
                client2.comm.sndr.PostMessage(msg);

                Console.ReadKey();

                Console.Write("\n  press key to exit: ");
                Console.ReadKey();

                client2.wait();
                Console.Write("\n\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught {0}", ex.Message);
            }
            Console.ReadKey();
        }
Ejemplo n.º 11
0
        void Disconnected(ClientMessages reason, string message)
        {
            ConnectedEvent.Reset();

            Connection.Dispose();
            Connection = null;

            if (!GameClosed)
            {
                Invoke(new MethodInvoker(Close));
            }

            string title;

            switch (reason)
            {
            default:
                title = "Disconnected";
                break;

            case ClientMessages.JoinDenied:
                title = "Join denied";
                break;

            case ClientMessages.Kicked:
                title = "Kicked";
                break;

            case ClientMessages.Timeout:
                title = "Timeout";
                break;

            case ClientMessages.ServerShutdown:
                title   = "Shutdown";
                message = "Server was shut down";
                break;
            }
            MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
Ejemplo n.º 12
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (UncompressedSize != 0UL)
            {
                hash ^= UncompressedSize.GetHashCode();
            }
            if (ServerMessages != 0)
            {
                hash ^= ServerMessages.GetHashCode();
            }
            if (ClientMessages != 0)
            {
                hash ^= ClientMessages.GetHashCode();
            }
            if (Payload.Length != 0)
            {
                hash ^= Payload.GetHashCode();
            }
            return(hash);
        }
Ejemplo n.º 13
0
        static void ReadUserMessage(ClientMessages id, GameClient client, PacketReader stream)
        {
            switch (id)
            {
            case ClientMessages.WorldLoadedMessage:
                GameClient.Messages.ReadLoadWorldMessage(stream, client);
                break;

            case ClientMessages.ScriptMessage:
                client.ScriptObject.ReadScriptMessage(stream);
                break;

            case ClientMessages.GuidedVobMessage:
                WorldObjects.VobGuiding.GuidedVob.Messages.ReadPosAng(stream, client, client.World);
                break;

            case ClientMessages.GuidedNPCMessage:
                WorldObjects.NPC.Messages.ReadPosAng(stream, client, client.World);
                break;

            case ClientMessages.ScriptCommandMessage:
                GameClient.Messages.ReadScriptCommandMessage(stream, client, client.World, false);
                break;

            case ClientMessages.ScriptCommandHeroMessage:
                GameClient.Messages.ReadScriptCommandMessage(stream, client, client.World, true);
                break;

            case ClientMessages.SpecatorPosMessage:
                GameClient.Messages.ReadSpectatorPosition(stream, client);
                break;

            default:
                Logger.LogWarning("Client sent unknown NetworkID '{0}'. Kicked: {1} IP:{2}", id, client.ID, client.SystemAddress);
                DisconnectClient(client);
                return;
            }
        }
Ejemplo n.º 14
0
        public override bool HandlePacket(Character character, Packet packet, ClientMessages opcode)
        {
            switch (opcode)
            {
            // /matchtable command, expects bool arg
            case ClientMessages.FIELD_TOURNAMENT_MATCHTABLE:
            {
                if (packet.ReadBool())
                {
                    SendAvatarInfo(character);
                }


                // BIG FAT NOTE: THE UI ONLY DISPLAYS 1, 2, 4 AND 8 USERS
                // DO NOT TRY TO FIX IT; THE UI DOESNT SUPPORT MORE

                var p = new Packet(ServerMessages.TOURNAMENT_MATCH_TABLE);
                // This one is nasty. We cannot write lots of data at once.
                for (var i = 0; i < SLOTS; i++)
                {
                    for (var j = 0; j < 6; j++)
                    {
                        p.WriteInt(MatchTable[i, j]);
                    }
                }
                var round = CurrentRound;
                if (round >= 100)
                {
                    round -= 100;
                }
                p.WriteByte((byte)round);
                character.SendPacket(p);
                return(true);
            }

            default: return(base.HandlePacket(character, packet, opcode));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Called each time a message arrives for this consumer.
        /// </summary>
        /// <remarks>
        /// </remarks>
        public override void HandleBasicDeliver(
            string consumerTag,
            ulong deliveryTag,
            bool redelivered,
            string exchange,
            string routingKey,
            IBasicProperties properties,
            byte[] body)
        {
            TMessage message = default;

            Task.Run(async() =>
            {
                try
                {
                    if ((Model?.IsClosed).GetValueOrDefault())
                    {
                        return;
                    }

                    message = BasicPropertiesHelper.DecodeMessage <TMessage>(properties, body);
                    if (message == null)
                    {
                        //wrong message shouldn't be in this queue so remove it without requeue
                        //not in the ClientMessages collection yet

                        Model.BasicReject(deliveryTag, false);
                    }

                    //process the messages once we hit the fetch count
                    try
                    {
                        await semaphoreSlim.WaitAsync();

                        if (MaxFetchCount > 1)
                        {
                            //add a message to process

                            ClientMessages.Add(deliveryTag, ProcessingMessage.Add(deliveryTag, message));

                            if (ClientMessages.Count == MaxFetchCount)
                            {
                                var processingCollection = ClientMessages.Take((int)MaxFetchCount).ToDictionary(k => k.Key, v => v.Value);

                                var toProcessMessages = processingCollection?.Where(v => v.Value.Message != null)?.Select(v => (TMessage)v.Value.Message);
                                //execute work action
                                if (multipleMessagesFunctionAsync != null)
                                {
                                    await multipleMessagesFunctionAsync?.Invoke(toProcessMessages);
                                }

                                if (multipleMessagesFunction != null)
                                {
                                    multipleMessagesFunction?.Invoke(toProcessMessages);
                                }

                                foreach (var processing in processingCollection)
                                {
                                    if (!Model.IsClosed)
                                    {
                                        ClientMessages.Remove(processing.Key);

                                        //ack the message
                                        Model.BasicAck(processing.Key, false);
                                    }
                                }
                            }

                            if (ClientMessages.Count > MaxFetchCount)
                            {
                                if (!Model.IsClosed)
                                {
                                    ClientMessages.Remove(deliveryTag);

                                    //reject and requeue message we are at max fetch count
                                    Model.BasicReject(deliveryTag, true);
                                }
                            }
                        }
                        else //process messages one at a time
                        {
                            if (!Model.IsClosed)
                            {
                                //if maxfetch is <= 1 then process and ack a single message

                                if (messageFunctionAsync != null)
                                {
                                    await messageFunctionAsync?.Invoke(message);
                                }

                                if (messageFunction != null)
                                {
                                    messageFunction?.Invoke(message);
                                }

                                if (multipleMessagesFunctionAsync != null)
                                {
                                    await multipleMessagesFunctionAsync?.Invoke(new TMessage[] { message });
                                }

                                if (multipleMessagesFunction != null)
                                {
                                    multipleMessagesFunction?.Invoke(new TMessage[] { message });
                                }

                                ClientMessages.Remove(deliveryTag);
                                Model.BasicAck(deliveryTag, false);
                            }
                        }
                    }
                    finally
                    {
                        LastMessageTime = DateTime.UtcNow;
                        semaphoreSlim.Release();
                    }
                }
                catch (Exception ex)
                {
                    //Model.BasicNack(deliveryTag, false, false);
                    Debug.WriteLine(ex.ToString(), "HandleBasicDeliver");
                    errorAction?.Invoke(ex, message);
                }
            });
        }
 /// <summary>
 /// The send message.
 /// </summary>
 /// <param name="clientMessage">
 /// The client message.
 /// </param>
 /// <param name="data">
 /// The data.
 /// </param>
 private void SendMessage(ClientMessages clientMessage, Bundle data)
 {
     Message m = Message.Obtain(null, (int)clientMessage);
     m.Data = data;
     try
     {
         this.serviceMessenger.Send(m);
     }
     catch (RemoteException e)
     {
         e.PrintStackTrace();
     }
 }
Ejemplo n.º 17
0
        public override void AC_OnPacketInbound(Packet packet)
        {
            ClientMessages header = 0;

            try
            {
                header = (ClientMessages)packet.ReadByte();

                if (!Loaded || Player?.Character == null)
                {
                    switch (header)
                    {
                    case ClientMessages.MIGRATE_IN:
                        OnPlayerLoad(packet);
                        break;     //updated
                    }
                }
                // Block packets as we are migrating
                else if (Server.Instance.InMigration == false || Server.Instance.IsNewServerInMigration)
                {
                    var character = Player.Character;

                    if (logPackets.Contains(header))
                    {
                        PacketLog.ReceivedPacket(packet, (byte)header, Server.Instance.Name, IP);
                    }

                    switch (header)
                    {
                    case ClientMessages.ENTER_PORTAL:
                        MapPacket.OnEnterPortal(packet, character);
                        break;

                    case ClientMessages.CHANGE_CHANNEL:
                        OnChangeChannel(character, packet);
                        break;

                    case ClientMessages.ENTER_CASH_SHOP:
                        OnEnterCashShop(character);
                        break;

                    case ClientMessages.MOVE_PLAYER:
                        MapPacket.HandleMove(character, packet);
                        break;

                    case ClientMessages.SIT_REQUEST:
                        MapPacket.HandleSitChair(character, packet);
                        break;

                    case ClientMessages.ENTER_TOWN_PORTAL:
                        MapPacket.HandleDoorUse(character, packet);
                        break;

                    case ClientMessages.CLOSE_RANGE_ATTACK:
                        AttackPacket.HandleMeleeAttack(character, packet);
                        break;

                    case ClientMessages.RANGED_ATTACK:
                        AttackPacket.HandleRangedAttack(character, packet);
                        break;

                    case ClientMessages.MAGIC_ATTACK:
                        AttackPacket.HandleMagicAttack(character, packet);
                        break;

                    case ClientMessages.TAKE_DAMAGE:
                        CharacterStatsPacket.HandleCharacterDamage(character, packet);
                        break;

                    case ClientMessages.CHAT:
                        MessagePacket.HandleChat(character, packet);
                        break;

                    case ClientMessages.GROUP_MESSAGE:
                        MessagePacket.HandleSpecialChat(character, packet);
                        break;

                    case ClientMessages.WHISPER:
                        MessagePacket.HandleCommand(character, packet);
                        break;

                    case ClientMessages.EMOTE:
                        MapPacket.SendEmotion(character, packet.ReadInt());
                        break;

                    case ClientMessages.NPC_TALK:
                        MapPacket.HandleNPCChat(character, packet);
                        break;

                    case ClientMessages.NPC_TALK_MORE:
                        NpcPacket.HandleNPCChat(character, packet);
                        break;

                    case ClientMessages.SHOP_ACTION:
                        NpcPacket.HandleNPCShop(character, packet);
                        break;

                    case ClientMessages.STORAGE_ACTION:
                        StoragePacket.HandleStorage(character, packet);
                        break;

                    case ClientMessages.ITEM_MOVE:
                        InventoryPacket.HandleInventoryPacket(character, packet);
                        break;

                    case ClientMessages.ITEM_USE:
                        InventoryPacket.HandleUseItemPacket(character, packet);
                        break;

                    case ClientMessages.SUMMON_BAG_USE:
                        InventoryPacket.HandleUseSummonSack(character, packet);
                        break;

                    case ClientMessages.CASH_ITEM_USE:
                        CashPacket.HandleCashItem(character, packet);
                        break;

                    case ClientMessages.RETURN_SCROLL_USE:
                        InventoryPacket.HandleUseReturnScroll(character, packet);
                        break;

                    case ClientMessages.SCROLL_USE:
                        InventoryPacket.HandleScrollItem(character, packet);
                        break;

                    case ClientMessages.DISTRIBUTE_AP:
                        CharacterStatsPacket.HandleStats(character, packet);
                        break;

                    case ClientMessages.HEAL_OVER_TIME:
                        CharacterStatsPacket.HandleHeal(character, packet);
                        break;

                    case ClientMessages.DISTRIBUTE_SP:
                        SkillPacket.HandleAddSkillLevel(character, packet);
                        break;

                    case ClientMessages.PREPARE_SKILL:
                        SkillPacket.HandlePrepareSkill(character, packet);
                        break;

                    case ClientMessages.GIVE_BUFF:
                        SkillPacket.HandleUseSkill(character, packet);
                        break;

                    case ClientMessages.CANCEL_BUFF:
                        SkillPacket.HandleStopSkill(character, packet);
                        break;

                    case ClientMessages.DROP_MESOS:
                        DropPacket.HandleDropMesos(character, packet.ReadInt());
                        break;

                    case ClientMessages.GIVE_FAME:
                        FamePacket.HandleFame(character, packet);
                        break;

                    case ClientMessages.CHAR_INFO_REQUEST:
                        MapPacket.SendPlayerInfo(character, packet);
                        break;

                    case ClientMessages.SPAWN_PET:
                        PetsPacket.HandleSpawnPet(character, packet.ReadShort());
                        break;

                    case ClientMessages.SUMMON_MOVE:
                        MapPacket.HandleSummonMove(character, packet);
                        break;

                    case ClientMessages.SUMMON_ATTACK:
                        AttackPacket.HandleSummonAttack(character, packet);
                        break;

                    case ClientMessages.SUMMON_DAMAGED:
                        MapPacket.HandleSummonDamage(character, packet);
                        break;

                    case ClientMessages.MOB_MOVE:
                        MobPacket.HandleMobControl(character, packet);
                        break;

                    case ClientMessages.NPC_ANIMATE:
                        MapPacket.HandleNPCAnimation(character, packet);
                        break;

                    case ClientMessages.PET_MOVE: PetsPacket.HandleMovePet(character, packet); break;

                    case ClientMessages.PET_INTERACTION: PetsPacket.HandleInteraction(character, packet); break;

                    case ClientMessages.PET_ACTION: PetsPacket.HandlePetAction(character, packet); break;

                    case ClientMessages.FIELD_CONTIMOVE_STATE:
                        MapPacket.OnContiMoveState(character, packet);
                        break;

                    case ClientMessages.DROP_PICK_UP:
                        DropPacket.HandlePickupDrop(character, packet);
                        break;

                    case ClientMessages.MESSENGER:
                        MessengerHandler.HandleMessenger(character, packet);
                        break;

                    case ClientMessages.MINI_ROOM_OPERATION:
                        MiniRoomPacket.HandlePacket(character, packet);
                        break;

                    case ClientMessages.FRIEND_OPERATION:
                        BuddyHandler.HandleBuddy(character, packet);
                        break;

                    case ClientMessages.PARTY_OPERATION:
                        PartyHandler.HandleParty(character, packet);
                        break;

                    case ClientMessages.DENY_PARTY_REQUEST:
                        PartyHandler.HandleDecline(character, packet);
                        break;

                    case ClientMessages.REACTOR_HIT:
                        ReactorPacket.HandleReactorHit(character, packet);
                        break;

                    case ClientMessages.REPORT_USER:
                        MiscPacket.ReportPlayer(character, packet);
                        break;


                    //this is a garbage opcode that i use when doing janky client packet workarounds. This is where packets go to die.
                    case ClientMessages.JUNK:
                        Program.MainForm.LogDebug("received junk packet");
                        break;

                    // eh.. ignore?
                    // Happens when one of the following buffs are set:
                    // Stun, Poison, Seal, Darkness, Weakness, Curse
                    // Maybe patch out of the client
                    case ClientMessages.CHARACTER_IS_DEBUFFED: break;

                    // TODO: Implement???
                    case ClientMessages.MOB_APPLY_CONTROL: break;

                    case ClientMessages.CLIENT_HASH: break;

                    case ClientMessages.PONG:
                        // Make sure we update the player online thing
                        RedisBackend.Instance.SetPlayerOnline(
                            character.UserID,
                            Server.Instance.GetOnlineId()
                            );

                        // Cleanup expired items
                        character.Inventory.CheckExpired();
                        break;

                    default:
                        if (character.Field.HandlePacket(character, packet, header) == false)
                        {
                            Program.MainForm.LogAppend(
                                "[{0}] Unknown packet received! " + packet,
                                header
                                );
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Program.MainForm.LogAppend($"---- ERROR ----\r\n{ex}");
                Program.MainForm.LogAppend($"Packet: {packet}");
                FileWriter.WriteLine(@"etclog\ExceptionCatcher.log", "[Game Server " + Server.Instance.ID + "][" + DateTime.Now + "] Exception caught: " + ex, true);
                //Disconnect();
            }


#if DEBUG
            if (packet.Length != packet.Position)
            {
                var packetStr = packet.ToString();
                packetStr = packetStr.Substring(0, packet.Position * 3 - 1) + "-x-" + packetStr.Substring(packet.Position * 3);

                log.Debug($"Did not read full message in packet: {header} {packetStr}");
            }
#endif
        }
Ejemplo n.º 18
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);
                }
            }
        }
Ejemplo n.º 19
0
        public override void AC_OnPacketInbound(Packet packet)
        {
            try
            {
                ClientMessages header = (ClientMessages)packet.ReadByte();


                if (!logIgnore.Contains(header))
                {
                    Common.Tracking.PacketLog.ReceivedPacket(packet, (byte)header, Server.Instance.Name, this.IP);
                }

                if (!Loaded)
                {
                    switch (header)
                    {
                    case ClientMessages.LOGIN_CHECK_PASSWORD:
                        OnCheckPassword(packet);
                        break;

                    case ClientMessages.CLIENT_CRASH_REPORT:
                        crashLogTmp = packet.ReadString();
                        if (crashLogTmp.Contains("LdrShutdownProcess"))
                        {
                            // Ignore
                            crashLogTmp = null;
                        }
                        else
                        {
                            Program.MainForm.LogAppend("Received a crashlog!!!");
                        }
                        break;

                    case ClientMessages.LOGIN_EULA:
                        OnConfirmEULA(packet);
                        break;
                    }
                }
                else
                {
                    switch (header)
                    {
                    // Ignore this one
                    case ClientMessages.LOGIN_CHECK_PASSWORD: break;

                    case ClientMessages.LOGIN_SELECT_CHANNEL:
                        OnChannelSelect(packet);
                        break;

                    case ClientMessages.LOGIN_WORLD_INFO_REQUEST:
                        OnWorldInfoRequest(packet);
                        break;

                    case ClientMessages.LOGIN_WORLD_SELECT:
                        OnWorldSelect(packet);
                        break;

                    case ClientMessages.LOGIN_CHECK_CHARACTER_NAME:
                        OnCharNamecheck(packet);
                        break;

                    case ClientMessages.LOGIN_SELECT_CHARACTER:
                        OnSelectCharacter(packet);
                        break;

                    case ClientMessages.LOGIN_SET_GENDER:
                        OnSetGender(packet);
                        break;

                    case ClientMessages.LOGIN_CHECK_PIN:
                        OnPinCheck(packet);
                        break;

                    case ClientMessages.LOGIN_CREATE_CHARACTER:
                        OnCharCreation(packet);
                        break;

                    case ClientMessages.LOGIN_DELETE_CHARACTER:
                        OnCharDeletion(packet);
                        break;

                    case ClientMessages.PONG:
                        RedisBackend.Instance.SetPlayerOnline(Player.ID, 1);
                        break;

                    case ClientMessages.CLIENT_HASH: break;

                    default:
                    {
                        var errorText = "Unknown packet found " + packet;
                        Server.Instance.ServerTraceDiscordReporter.Enqueue(errorText);
                        Program.MainForm.LogAppend(errorText);

                        break;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                var errorText = "Exception caught: " + ex + ", packet: " + packet;
                Server.Instance.ServerTraceDiscordReporter.Enqueue(errorText);
                Program.MainForm.LogAppend(errorText);
                log.Error(ex);
                Disconnect();
            }
        }
Ejemplo n.º 20
0
 internal static PacketWriter SetupStream(ClientMessages id)
 {
     packetWriter.Reset();
     packetWriter.Write((byte)id);
     return(packetWriter);
 }
Ejemplo n.º 21
0
 protected virtual void OnPlayerDisconnecting(Player p, ClientMessages reason)
 {
 }
Ejemplo n.º 22
0
 public async override Task OnReceivePlayerMessage(JToken client, string connectionId)
 {
     ClientMessages.Add(client.ToString());
     await SendToPresenter(connectionId, "test");
 }
Ejemplo n.º 23
0
        private void QueueWaitingCheckTask()
        {
            //ensure queues are processed if queue count is < _maxfetchcount after a time elasped of no messages incoming (waiting)
            Task.Run(async() =>
            {
                while (true)
                {
                    try
                    {
                        if (DateTime.UtcNow.Subtract(LastMessageTime).TotalSeconds > 5)
                        {
                            try
                            {
                                await semaphoreSlim.WaitAsync();

                                var processingCollection = ClientMessages.Take((int)MaxFetchCount).ToDictionary(k => k.Key, v => v.Value);

                                if (!(Model?.IsClosed).GetValueOrDefault())
                                {
                                    BasicGetResult messageResult = null;


                                    try { messageResult = Model?.BasicGet(QueueName, false); }
                                    catch (Exception ex)
                                    {
                                        Debug.WriteLine(ex.ToString(), "QueueWaitingCheckTask => BasicGet");
                                        queueWaitErrorAction?.Invoke(ex);
                                    }

                                    //flush the queue until we reach max or null
                                    while (messageResult != null & processingCollection.Count < (int)MaxFetchCount)
                                    {
                                        var message = BasicPropertiesHelper.DecodeMessage <TMessage>(messageResult.BasicProperties, messageResult.Body);
                                        if (!processingCollection.ContainsKey(messageResult.DeliveryTag))
                                        {
                                            processingCollection.Add(messageResult.DeliveryTag, ProcessingMessage.Add(messageResult.DeliveryTag, message));
                                        }

                                        messageResult = Model?.BasicGet(QueueName, false);
                                    }
                                }

                                if (processingCollection?.Count > 0)
                                {
                                    if (!Model.IsClosed)
                                    {
                                        //both of these should not be implemented one or the other

                                        //if single message handler is created
                                        var processedMessage = processingCollection.Values.Select(v => (TMessage)v.Message).FirstOrDefault();
                                        if (processedMessage != null)
                                        {
                                            if (messageFunctionAsync != null)
                                            {
                                                await messageFunctionAsync?.Invoke(processedMessage);
                                            }

                                            if (messageFunction != null)
                                            {
                                                messageFunction?.Invoke(processedMessage);
                                            }
                                        }

                                        if (processingCollection?.Values != null)
                                        {
                                            var messages = processingCollection.Values?.Where(v => v.Message != null).Select(v => (TMessage)v.Message);
                                            //if multi messagehandler is created
                                            if (multipleMessagesFunctionAsync != null)
                                            {
                                                await multipleMessagesFunctionAsync?.Invoke(messages);
                                            }

                                            if (multipleMessagesFunction != null)
                                            {
                                                multipleMessagesFunction?.Invoke(messages);
                                            }
                                        }
                                    }
                                    //ack the messages
                                    foreach (var processing in processingCollection)
                                    {
                                        //remove processed message
                                        if (!Model.IsClosed)
                                        {
                                            ClientMessages.Remove(processing.Key);
                                            Model.BasicAck(processing.Key, false);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                LastMessageTime = DateTime.UtcNow;
                                semaphoreSlim.Release();
                            }
                        }
                        await Task.Delay(100);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString(), "QueueWaitingCheckTask");
                        queueWaitErrorAction?.Invoke(ex);
                    }
                } //while
            }).ConfigureAwait(false); //Task.Run
        }