Ejemplo n.º 1
0
        public override void HandleMessage(INetPacket packet)
        {
            Debug.WriteLine($"Message received: \"{packet.GetType().Name}\" ({Id})");

            if (Index < 2)
            {
                var ser = (BattleServer)Server;
                switch (packet)
                {
                case PBEActionsResponsePacket arp:
                    ser.ActionsSubmitted(this, arp.Actions);
                    break;

                case PBEPartyResponsePacket prp:
                    Party = prp.Party;
                    ser.PartySubmitted(this);
                    break;

                case PBESwitchInResponsePacket sirp:
                    ser.SwitchesSubmitted(this, sirp.Switches);
                    break;
                }
            }

            ResetEvent.Set();
        }
        private PBEBattle(BinaryReader r)
        {
            ushort version = r.ReadUInt16();

            Settings = new PBESettings(r);
            Settings.MakeReadOnly();
            BattleFormat = (PBEBattleFormat)r.ReadByte();
            Teams        = new PBETeams(this);

            var packetProcessor = new PBEPacketProcessor(this);
            int numEvents       = r.ReadInt32();

            for (int i = 0; i < numEvents; i++)
            {
                INetPacket packet = packetProcessor.CreatePacket(r.ReadBytes(r.ReadInt16()));
                switch (packet)
                {
                case PBEWinnerPacket wp:
                {
                    Winner = wp.WinningTeam;
                    break;
                }
                }
                Events.Add(packet);
            }

            BattleState = PBEBattleState.Ended;
            OnStateChanged?.Invoke(this);
        }
Ejemplo n.º 3
0
 public virtual void     Send(INetPacket packet)
 {
     if (session.Connected())
     {
         session.SendPacket(packet);
     }
 }
Ejemplo n.º 4
0
        public override void HandleMessage(INetPacket packet)
        {
            Debug.WriteLine($"Message received: \"{packet.GetType().Name}\" ({BattleId})");
            if (Socket == null || ResetEvent.SafeWaitHandle.IsClosed)
            {
                return;
            }
            ResetEvent.Set();

            if (BattleId < 2)
            {
                var ser = (BattleServer)Server;
                switch (packet)
                {
                case PBEActionsResponsePacket arp:
                {
                    ser.ActionsSubmitted(this, arp.Actions);
                    break;
                }

                case PBEPartyResponsePacket prp:
                {
                    Party = prp.Party;
                    ser.PartySubmitted(this);
                    break;
                }

                case PBESwitchInResponsePacket sirp:
                {
                    ser.SwitchesSubmitted(this, sirp.Switches);
                    break;
                }
                }
            }
        }
Ejemplo n.º 5
0
    public static void Decode(byte[] buffer, INetPacket packet)
    {
        ushort    IdSize = sizeof(ushort);
        ByteArray bytes  = new ByteArray(buffer, IdSize);

        packet.decode(bytes);
    }
Ejemplo n.º 6
0
 public void SendData(INetPacket data)
 {
     if (data.DestinationAddress != null)
     {
         var targetIf = RouteTableModule.GetTargetInterface(data.DestinationAddress, interfaces);
         if (targetIf != null)
         {
             targetIf.SendData(data);
             return;
         }
         else
         {
             var routeTarget = RouteTableModule.GetRoute(data.DestinationAddress, interfaces, routes, DefaultRoute);
             if (routeTarget != null)
             {
                 targetIf = RouteTableModule.GetTargetInterface(routeTarget, interfaces);
                 if (targetIf != null)
                 {
                     targetIf.SendData(data);
                     return;
                 }
             }
         }
         EmulatorLogger.Log(LogLevel.Info, EventType.RouteNotFound, string.Empty);
     }
 }
Ejemplo n.º 7
0
    private void ProcessPackets()
    {
        short id = 0;

        while (!pause && buffers.Count > 0)
        {
            byte[] packBuff = PacketCrypto.Decode((byte[])buffers.Dequeue());
            id = Packet.GetMsgID(packBuff);
            Handler handler = (Handler)events[id];
            if (handler != null)
            {
                INetPacket packet = handler.packet.Create();
                handler.packet = packet;
                Packet.Decode(packBuff, handler.packet);
                Debug.Log("id: " + id.ToString() + ", packet: " + handler.packet);
                PostEvent(id, handler.packet);
            }
        }

        if (error_id != 0)
        {
            PostSocketEvent(error_id, res);
            error_id = 0;
            res      = String.Empty;
            client.Close();
        }
    }
Ejemplo n.º 8
0
 private void SendToStream(INetPacket p)
 {
     try
     {
         lock (Stream)
         {
             var Packet = (MinecraftPacket)p;
             Packet.Client = this;
             Packet.Initialize(0, null);
             //Here we can add Length & Id etc.
             Packet.Write <VarInt>(Packet.Id);
             Packet.WritePacket();
             var v = new MemoryStream();
             new MinecraftVarInt(v).Write(Packet.Buffer.Length);
             var l  = v.ToArray();
             var l2 = JoinArrays(l, Packet.Buffer);
             //Caught! we need to add @Crypto too
             Stream.Write(l2, 0, l2.Length);
             Console.WriteLine($"Send {Packet.GetType().Name} ({Packet.Id.ToString("X")}) ({l2.Length})");
             Stream.Flush();
         }
     }
     catch (SocketException ex)
     {
         this.Close();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         throw;
     }
 }
 public override void SendData(INetPacket data)
 {
     if (otherInterface != null) {
         EmulatorLogger.Log(LogLevel.Info, EventType.PacketSend, this.Name);
         otherInterface.ReceiveData(new NetPacket(this.HardwareAddress, otherInterface.HardwareAddress, data.SourceAddress ?? this.Address, data.DestinationAddress));
     } else {
         EmulatorLogger.Log(LogLevel.Error, EventType.NotConnected, "There are no connected devie: " + this.Name);
     }
 }
Ejemplo n.º 10
0
        public void SendTo(INetPacket packet, NetUser user)
        {
            lock (Clients)
                if (!Clients.Contains(user))
                {
                    throw new ArgumentException();
                }

            user.Send(packet);
        }
Ejemplo n.º 11
0
 public virtual void SendToAll(INetPacket packet, Func <NetUser, bool> predicate)
 {
     lock (Clients)
         foreach (var v in Clients)
         {
             if (predicate(v))
             {
                 SendTo(packet, v);
             }
         }
 }
Ejemplo n.º 12
0
 public override void SendData(INetPacket data)
 {
     if (otherInterface != null)
     {
         EmulatorLogger.Log(LogLevel.Info, EventType.PacketSend, this.Name);
         otherInterface.ReceiveData(new NetPacket(this.HardwareAddress, otherInterface.HardwareAddress, data.SourceAddress ?? this.Address, data.DestinationAddress));
     }
     else
     {
         EmulatorLogger.Log(LogLevel.Error, EventType.NotConnected, "There are no connected devie: " + this.Name);
     }
 }
Ejemplo n.º 13
0
        public virtual bool SendPacket(INetPacket packt)
        {
            _SendList.Enqueue(packt);
            TCPSocketToken token = Token;

            if (token == null || !token.IsConnect)
            {
                return(false);
            }
            token.TrySend();
            return(true);
        }
Ejemplo n.º 14
0
 public virtual void SendData(INetPacket data)
 {
     if (otherInterface != null)
     {
         EmulatorLogger.Log(LogLevel.Info, EventType.PacketSend, this.Name);
         otherInterface.ReceiveData(new NetPacket(this.HardwareAddress, otherInterface.HardwareAddress, data.SourceAddress, data.DestinationAddress));
     }
     else
     {
         EmulatorLogger.Log(LogLevel.Info, EventType.NotConnected, this.Name);
     }
 }
Ejemplo n.º 15
0
 public virtual void ReceiveData(INetPacket data)
 {
     EmulatorLogger.Log(LogLevel.Info, EventType.PacketRecived, this.Name);
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (data.DestinationHardwareAddress == this.HardwareAddress)
     {
         parent.ReceiveData(data, this);
     }
 }
Ejemplo n.º 16
0
 public void Clear()
 {
     lock (this)
     {
         Close();
         SetSocket(null);
         SendList       = null;
         currSendPacket = null;
         writeBuffer.SetPacket(null);
         recivePacket = null;
         currPackHead.Reset();
     }
 }
Ejemplo n.º 17
0
    /// <summary>
    /// Sends the packet.
    /// </summary>
    /// <param name="packet">Packet.</param>
    public override void    SendPacket(INetPacket packet)
    {
        packet.Finish();

        lock (sendQueue) {
            sendQueue.Enqueue(packet);

                        #if UNITY_EDITOR
            UnityEngine.Debug.Log(string.Format("Send queue count ({0}))",
                                                sendQueue.Count));
                        #endif
        }
    }
Ejemplo n.º 18
0
 // Use a StreamWriter to send a message to server.
 public void Send(INetPacket packet)
 {
     if (first_send)
     {
         //string header = "GET / HTTP/1.1\r\nHost: " + m_ip + ":" + m_port + "\r\n\r\n";
         string header = "tgw_l7_forward\r\nHost: " + m_ip + ":" + m_port + "\r\n\r\n";
         Debug.Log(header);
         byte[] bytes = System.Text.Encoding.Default.GetBytes(header);
         Send(bytes);
         first_send = false;
     }
     SendImpl(packet);
 }
Ejemplo n.º 19
0
 public static byte[] Encode(INetPacket packet)
 {
     if (packet != null)
     {
         ByteArray bytes = new ByteArray();
         packet.build(bytes);
         byte[]      bodyBytes = PacketCrypto.Encode(bytes.GetBytes());
         List <byte> pack      = swab32(bodyBytes.Length);
         pack.AddRange(bodyBytes);
         return(pack.ToArray());
     }
     return(null);
 }
Ejemplo n.º 20
0
    /// <summary>
    /// Posts the packet.
    /// </summary>
    /// <param name="IPacket">I packet.</param>
    public override void    PostPacket(INetPacket packet)
    {
        packet.Finish();

        lock (recvQueue) {
            recvQueue.Enqueue(packet);

                        #if UNITY_EDITOR
            UnityEngine.Debug.Log(string.Format("Packet type({0}) size({1}) Enqueue queue({2})",
                                                packet.Type, packet.Size, recvQueue.Count));
                        #endif
        }
    }
Ejemplo n.º 21
0
    /// <summary>
    /// Raises the send thread event.
    /// </summary>
    /// <param name="o">O.</param>
    public void             OnSendThread()
    {
        try{
            if (!socket.Poll(10000000, SelectMode.SelectWrite))
            {
                socket.Close();
            }
            else
            {
                while (true)
                {
                    if (!Connected())
                    {
                        break;
                    }

                    if (sendQueue.Count > 0)
                    {
                        INetPacket packet = default(INetPacket);

                        lock (sendQueue) {
                            packet = sendQueue.Dequeue();
                        }

                        if (packet != null)
                        {
                            int nSendBytes = socket.Send(packet.GetBytes(), 0, packet.Size + sizeof(int), SocketFlags.None);

                                                        #if UNITY_EDITOR
                            UnityEngine.Debug.Log(string.Format("Send packet type({0}) size({1})",
                                                                packet.Type, nSendBytes));
                                                        #endif
                        }
                    }

                    Thread.Sleep(10);
                }
            }
        } catch (Exception e) {
                        #if UNITY_EDITOR
            UnityEngine.Debug.LogError(e.Message);
                        #endif

            PostPacket(
                new INetPacket(PacketType.SOCKET_DISCONNECT)
                );
        }

        sendThread.Abort();
    }
Ejemplo n.º 22
0
 public override void HandlePacket(INetPacket v)
 {
     lock (Stream)
     {
         var p = (MinecraftPacket)v;
         //Here any Read Logic Goes
         var id     = p.Read <VarInt>();
         var Packet = GetPacket(id, true);
         Console.WriteLine($"Received Packet {Packet.Id.ToString("X")} ({Packet.GetType().Name}) ({Packet.Length})");
         Packet.Client = this;
         Packet.Initialize(p.Length, p.MemoryStream);
         Packet.ReadPacket();
         Stream.Flush();
     }
 }
Ejemplo n.º 23
0
 public void SendData(INetPacket data)
 {
     if (busyInterface != null)
     {
         for (int i = 0; i < this.interfaces.Count; i++)
         {
             if (busyInterface != i)
             {
                 var ipInterface = this.interfaces[i];
                 Task.Run(() => {
                     var transmitData = data.Clone( );
                     ipInterface.SendData(transmitData);
                 });
             }
         }
     }
 }
Ejemplo n.º 24
0
    /// <summary>
    /// Determines whether the specified <see cref="INetPacket"/> is equal to the current <see cref="INetPacket"/>.
    /// </summary>
    /// <param name="other">The <see cref="INetPacket"/> to compare with the current <see cref="INetPacket"/>.</param>
    /// <returns><c>true</c> if the specified <see cref="INetPacket"/> is equal to the current <see cref="INetPacket"/>; otherwise, <c>false</c>.</returns>
    public bool Equals(INetPacket other)
    {
        if (size == other.Size)
        {
            byte[] otherData = other.GetBytes();
            for (int i = 0; i < size; i++)
            {
                if (data[i] != otherData[i])
                {
                    return(false);
                }
            }
            return(true);
        }

        return(false);
    }
Ejemplo n.º 25
0
        public void ReceiveData(INetPacket data, INetHwInterface iface)
        {
            int ifaceNo = this.interfaces.FindIndex(x => x.Equals(iface));

            foreach (var ipInterface in interfaces)
            {
                if (ipInterface.Address != null && ipInterface.Address.Value.Address == data.DestinationAddress?.Address)
                {
                    return;
                }
            }
            if (data.TTL > 0)
            {
                data.TTL--;
                this.SendData(data);
            }
        }
Ejemplo n.º 26
0
 public void ReceiveData(INetPacket data, INetHwInterface iface)
 {
     if (busyInterface != null) {
         EmulatorLogger.Log(LogLevel.Error, EventType.HubPacketColision, this.Name);
         return;
     } else {
         int ifaceNo = this.interfaces.FindIndex(x => ReferenceEquals(x, iface));
         if (ifaceNo >= 0) {
             busyInterface = ifaceNo;
             if (data.TTL > 0) {
                 data.TTL--;
                 this.SendData(data);
             }
             busyInterface = null;
         }
     }
 }
Ejemplo n.º 27
0
        private static void Battle_OnNewEvent(PBEBattle battle, INetPacket packet)
        {
            try
            {
                switch (packet)
                {
                case PBEActionsRequestPacket arp:
                {
                    PBETeam         team    = arp.Team;
                    PBETurnAction[] actions = PBEAI.CreateActions(team);
                    if (!PBEBattle.AreActionsValid(team, actions))
                    {
                        throw new Exception($"{team.TrainerName}'s AI created invalid actions!");
                    }
                    PBEBattle.SelectActionsIfValid(team, actions);
                    break;
                }

                case PBESwitchInRequestPacket sirp:
                {
                    PBETeam       team     = sirp.Team;
                    PBESwitchIn[] switches = PBEAI.CreateSwitches(team);
                    if (!PBEBattle.AreSwitchesValid(team, switches))
                    {
                        throw new Exception($"{team.TrainerName}'s AI created invalid switches!");
                    }
                    PBEBattle.SelectSwitchesIfValid(team, switches);
                    break;
                }

                case PBETurnBeganPacket tbp:
                {
                    Console.SetOut(_oldWriter);
                    DateTime time = DateTime.Now;
                    Console.WriteLine($"Emulating turn {tbp.TurnNumber}... ({time.Hour:D2}:{time.Minute:D2}:{time.Second:D2}:{time.Millisecond:D3})");
                    Console.SetOut(_writer);
                    break;
                }
                }
            }
            catch (Exception e)
            {
                CatchException(e);
            }
        }
Ejemplo n.º 28
0
        /*
         * private byte[] HeadBuffer = new byte[6];
         * private int HeadLenth;
         * private int HeadWritePos;
         */
        public void SetPacket(INetPacket packet)
        {
            if (Packet == packet)
            {
                return;
            }
            Packet   = packet;
            WritePos = 0;

            /*
             * HeadLenth = 0;
             * HeadWritePos = 0;
             * if (packet != null)
             * {
             *  WriteLength();
             * }
             */
        }
Ejemplo n.º 29
0
        public override void HandleMessage(INetPacket packet)
        {
            Debug.WriteLine($"Message received: \"{packet.GetType().Name}\" ({BattleId})");
            if (Socket == null || ResetEvent.SafeWaitHandle.IsClosed)
            {
                return;
            }
            ResetEvent.Set();

            if (BattleId < 2)
            {
                var ser = (BattleServer)Server;
                switch (packet)
                {
                case PBEActionsResponsePacket arp:
                {
                    ser.ActionsSubmitted(this, arp.Actions);
                    break;
                }

                case PBEPartyResponsePacket prp:
                {
                    Console.WriteLine($"Received team from {TrainerName}!");
                    if (TeamShell == null)
                    {
                        TeamShell = prp.TeamShell;
                        ser.PartySubmitted(this);
                    }
                    else
                    {
                        Console.WriteLine("Team submitted multiple times!");
                    }
                    break;
                }

                case PBESwitchInResponsePacket sirp:
                {
                    ser.SwitchesSubmitted(this, sirp.Switches);
                    break;
                }
                }
            }
        }
Ejemplo n.º 30
0
 public void OnSendCompleted()
 {
     lock (this)
     {
         if (currSendPacket != null && SendList != null)
         {
             if (writeBuffer.IsComplete())
             {
                 INetPacket pack = null;
                 if (SendList.TryPeek(out pack) && pack == currSendPacket)
                 {
                     SendList.TryDequeue(out pack);
                 }
                 currSendPacket = null;
             }
         }
         Send();
     }
 }
Ejemplo n.º 31
0
    /// <summary>
    /// Update this instance.
    /// </summary>
    public virtual void     Update()
    {
        if (session != null)
        {
            Queue <INetPacket> recvQueue = session.GetPacketQueue();

            while (recvQueue.Count > 0)
            {
                INetPacket packet = null;

                lock (recvQueue) {
                    packet = recvQueue.Dequeue();
                }

                if (packet != null)
                {
                    netFunc.call(new XNetLuaPacket(packet));
                }
            }
        }
    }
Ejemplo n.º 32
0
 public void ReceiveData(INetPacket data, INetHwInterface iface)
 {
     if (busyInterface != null)
     {
         EmulatorLogger.Log(LogLevel.Error, EventType.HubPacketColision, this.Name);
         return;
     }
     else
     {
         int ifaceNo = this.interfaces.FindIndex(x => ReferenceEquals(x, iface));
         if (ifaceNo >= 0)
         {
             busyInterface = ifaceNo;
             if (data.TTL > 0)
             {
                 data.TTL--;
                 this.SendData(data);
             }
             busyInterface = null;
         }
     }
 }
Ejemplo n.º 33
0
 public void SendData(INetPacket data)
 {
     if (busyInterface != null) {
         for (int i = 0; i < this.interfaces.Count; i++) {
             if (busyInterface != i) {
                 var ipInterface = this.interfaces[i];
                 Task.Run(( ) => {
                     var transmitData = data.Clone( );
                     ipInterface.SendData(transmitData);
                 });
             }
         }
     }
 }
Ejemplo n.º 34
0
 public override void ReceiveData(INetPacket data)
 {
     base.ReceiveData(data);
 }
Ejemplo n.º 35
0
 public void ReceiveData(INetPacket data, INetHwInterface iface)
 {
     #if DEBUG
     System.Diagnostics.Debug.WriteLine("{0} recived {1}", this.Name, data);
     #endif
 }
Ejemplo n.º 36
0
 public virtual void SendData(INetPacket data)
 {
     if (otherInterface != null) {
         EmulatorLogger.Log(LogLevel.Info, EventType.PacketSend, this.Name);
         otherInterface.ReceiveData(new NetPacket(this.HardwareAddress, otherInterface.HardwareAddress, data.SourceAddress, data.DestinationAddress));
     } else {
         EmulatorLogger.Log(LogLevel.Info, EventType.NotConnected, this.Name);
     }
 }
Ejemplo n.º 37
0
 public virtual void ReceiveData(INetPacket data)
 {
     EmulatorLogger.Log(LogLevel.Info, EventType.PacketRecived, this.Name);
     if (data == null)
         throw new ArgumentNullException("data");
     if (data.DestinationHardwareAddress == this.HardwareAddress)
         parent.ReceiveData(data, this);
 }
Ejemplo n.º 38
0
 public void SendData(INetPacket data)
 {
     if (data.DestinationAddress != null) {
         var targetIf = RouteTableModule.GetTargetInterface(data.DestinationAddress, interfaces);
         if (targetIf != null) {
             targetIf.SendData(data);
             return;
         } else {
             var routeTarget = RouteTableModule.GetRoute(data.DestinationAddress, interfaces, routes, DefaultRoute);
             if (routeTarget != null) {
                 targetIf = RouteTableModule.GetTargetInterface(routeTarget, interfaces);
                 if (targetIf != null) {
                     targetIf.SendData(data);
                     return;
                 }
             }
         }
         EmulatorLogger.Log(LogLevel.Info, EventType.RouteNotFound, string.Empty);
     }
 }
Ejemplo n.º 39
0
 public void ReceiveData(INetPacket data, INetHwInterface iface)
 {
     int ifaceNo = this.interfaces.FindIndex(x => x.Equals(iface));
     foreach (var ipInterface in interfaces) {
         if (ipInterface.Address != null && ipInterface.Address.Value.Address == data.DestinationAddress?.Address) {
             return;
         }
     }
     if (data.TTL > 0) {
         data.TTL--;
         this.SendData(data);
     }
 }