Ejemplo n.º 1
0
		public override void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
		{
			if (this.Id == 0)
			{
				throw new Exception("UChannel已经被Dispose, 不能发送消息");
			}
			this.socket.SendAsync(buffer, channelID, flags);
		}
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/> class.
 /// </summary>
 /// <param name="data">
 /// Data of the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>.
 /// </param>
 /// <param name="direction">
 /// <see cref="Kamilla.Network.TransferDirection"/> of
 /// the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>.
 /// </param>
 /// <param name="flags">
 /// The <see cref="Kamilla.Network.PacketFlags"/> of
 /// the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>.
 /// </param>
 /// <param name="wowFlags">
 /// The <see cref="Kamilla.Network.Protocols.Wow.WowPacketFlags"/> of
 /// the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>.
 /// </param>
 /// <param name="arrivalTicks">
 /// Number of milliseconds passed from the Operation System start to the packet arrival event.
 /// </param>
 /// <param name="arrivalTime">
 /// An instance of <see cref="System.DateTime"/> representing the moment when
 /// the packet <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/> arrived.
 /// </param>
 /// <param name="opcode">
 /// The opcode of the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>.
 /// </param>
 /// <param name="connectionId">
 /// The connection id of the new <see cref="Kamilla.Network.Protocols.Wow.WowPacket"/>.
 /// </param>
 public WowPacket(byte[] data, TransferDirection direction, PacketFlags flags, WowPacketFlags wowFlags,
     DateTime arrivalTime, uint arrivalTicks, uint opcode, int connectionId)
     : base(data, direction, flags, arrivalTime, arrivalTicks)
 {
     m_opcode = opcode;
     m_connectionId = connectionId;
     m_wowFlags = wowFlags;
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of <see cref="Kamilla.Network.Packet"/> class
 /// with the specified data, <see cref="Kamilla.Network.TransferDirection"/>,
 /// <see cref="Kamilla.Network.PacketFlags"/>, and arrival time and ticks.
 /// </summary>
 /// <param name="data">
 /// Data of the new <see cref="Kamilla.Network.Packet"/>.
 /// </param>
 /// <param name="direction">
 /// <see cref="Kamilla.Network.TransferDirection"/> of the new <see cref="Kamilla.Network.Packet"/>.
 /// </param>
 /// <param name="flags">
 /// <see cref="Kamilla.Network.PacketFlags"/> of the new <see cref="Kamilla.Network.Packet"/>.
 /// </param>
 /// <param name="arrivalTicks">
 /// Number of milliseconds passed from the Operation System start to the packet arrival event.
 /// </param>
 /// <param name="arrivalTime">
 /// An instance of <see cref="System.DateTime"/> representing the moment when
 /// the packet <see cref="Kamilla.Network.Packet"/> arrived.
 /// </param>
 public Packet(byte[] data, TransferDirection direction, PacketFlags flags,
     DateTime arrivalTime, uint arrivalTicks)
 {
     m_arrivalDateTime = arrivalTime;
     m_arrivalTicks = arrivalTicks;
     m_data = data;
     m_direction = direction;
     m_flags = flags;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Sets the value of the specified flag.
 /// </summary>
 protected void SetFlag(PacketFlags flag, bool value)
 {
     if (value)
     {
         _packetFlags |= flag;
     }
     else
     {
         _packetFlags &= ~flag;
     }
 }
Ejemplo n.º 5
0
		public override void SendAsync(
				byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
		{
			if (!this.isConnected)
			{
				BufferInfo info = new BufferInfo { Buffer = buffer, ChannelID = channelID, Flags = flags };
				this.queue.Enqueue(info);
				return;
			}
			this.socket.SendAsync(buffer, channelID, flags);
		}
Ejemplo n.º 6
0
		public UPacket(byte[] data, PacketFlags flags = PacketFlags.None)
		{
			if (data == null)
			{
				throw new ArgumentNullException("data");
			}
			this.packet = NativeMethods.ENetPacketCreate(data, (uint) data.Length, flags);
			if (this.packet == IntPtr.Zero)
			{
				throw new UException("Packet creation call failed");
			}
		}
Ejemplo n.º 7
0
        public void Create(byte[] data, int length, PacketFlags flags)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (length < 0 || length > data.Length)
            {
                throw new ArgumentOutOfRangeException();
            }

            nativePacket = Native.enet_packet_create(data, (IntPtr)length, flags);
        }
Ejemplo n.º 8
0
 public override void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
 {
     if (this.Id == 0)
     {
         throw new Exception("TChannel已经被Dispose, 不能发送消息");
     }
     byte[] size = BitConverter.GetBytes((ushort)buffer.Length);
     this.sendBuffer.SendTo(size);
     this.sendBuffer.SendTo(buffer);
     if (this.isConnected)
     {
         this.StartSend();
     }
 }
Ejemplo n.º 9
0
        private static bool Broadcast(byte[] buffer, Channel channelNo, PacketFlags packetFlags = PacketFlags.None)
        {
            if (buffer.Length >= 8)
            {
                buffer = BlowFish.Encrypt(buffer);
                fixed(byte *b = buffer)
                {
                    var packet = enet_packet_create(new IntPtr(b), new IntPtr(buffer.Length), packetFlags);

                    enet_host_broadcast(LoLServer.GetServer(), (byte)channelNo, packet);
                }

                return(true);
        }
Ejemplo n.º 10
0
        public void Create(IntPtr data, int offset, int length, PacketFlags flags)
        {
            if (data == IntPtr.Zero)
            {
                throw new ArgumentNullException("data");
            }

            if (offset < 0 || length < 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            nativePacket = Native.enet_packet_create_offset(data, (IntPtr)length, (IntPtr)offset, flags);
        }
Ejemplo n.º 11
0
        public void Send(MessageType type, Peer peer, byte[] data, PacketFlags flags)
        {
            Packet packet = default(Packet);

            byte[] buffer = new byte[MessageConfig.MESSAGE_LEN + data.Length];

            byte[] byteType = BitConverter.GetBytes((ushort)type);
            Array.Copy(byteType, buffer, MessageConfig.MESSAGE_LEN);

            Array.Copy(data, 0, buffer, MessageConfig.MESSAGE_LEN, data.Length);

            packet.Create(buffer, flags);
            peer.Send(0, ref packet);
        }
Ejemplo n.º 12
0
        public void Create(byte[] data, int offset, int length, PacketFlags flags)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (offset < 0 || length < 0 || length > data.Length - offset)
            {
                throw new ArgumentOutOfRangeException();
            }

            _packet = new LENet.Packet((uint)length, (LENet.PacketFlags)flags);
            Array.Copy(data, offset, _packet.Data, 0, length);
        }
Ejemplo n.º 13
0
        public override void Send(List <byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
        {
            int size = buffers.Select(b => b.Length).Sum();

            byte[] sizeBuffer = BitConverter.GetBytes(size);
            this.sendBuffer.SendTo(sizeBuffer);
            foreach (byte[] buffer in buffers)
            {
                this.sendBuffer.SendTo(buffer);
            }
            if (!this.isSending && this.isConnected)
            {
                this.StartSend();
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Send a message to an array of clients.
        /// </summary>
        /// <param name="message">The message to send</param>
        /// <param name="clients">The clients to send to</param>
        /// <param name="channel">The channel to send the message through</param>
        private void SendMessage(Message message, PacketFlags flags, byte channel, IClient[] clients)
        {
            // Extract the array of peers from the clients
            // TODO: Figure out a more efficient way for this.
            int length = clients.Length;

            Peer[] peers = new Peer[length];
            for (int i = 0; i < length; ++i)
            {
                ClientManager.TryGetClient(clients[i].Id, out var client);
                peers[i] = client.Peer;
            }

            SendMessage(message, flags, channel, peers);
        }
Ejemplo n.º 15
0
        public void SendAsync(byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
        {
            if (!isConnected)
            {
                sendQueue.Enqueue(new BufferInfo {
                    Buffer = data, ChannelID = channelID, Flags = flags
                });
                return;
            }
            UPacket packet = new UPacket(data, flags);

            NativeMethods.ENetPeerSend(this.PeerPtr, channelID, packet.PacketPtr);
            // enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
            packet.PacketPtr = IntPtr.Zero;
        }
Ejemplo n.º 16
0
        public void Create(byte[] data, int offset, int length, PacketFlags flags)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (offset < 0 || length < 0 || length > data.Length - offset)
            {
                throw new ArgumentOutOfRangeException();
            }

            fixed(byte *bytes = data)
            {
                Create(bytes + offset, length, flags);
            }
        }
Ejemplo n.º 17
0
		public override void Send(List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
		{
			if (this.Id == 0)
			{
				throw new Exception("UChannel已经被Dispose, 不能发送消息");
			}
			int size = buffers.Select(b => b.Length).Sum();
			var buffer = new byte[size];
			int index = 0;
			foreach (byte[] bytes in buffers)
			{
				Array.Copy(bytes, 0, buffer, index, bytes.Length);
				index += bytes.Length;
			}
			this.socket.SendAsync(buffer, channelID, flags);
		}
        public EchoServer(Configuration config, BenchmarkStatistics benchmarkStatistics) : base(config)
        {
            this.config = config;
            this.benchmarkStatistics = benchmarkStatistics;
            timeout     = Utilities.CalculateTimeout(this.config.ServerTickRate);
            packetFlags = ENetBenchmark.GetPacketFlags(config.Transmission);

            host    = new Host();
            address = new Address();

            address.Port = (ushort)config.Port;
            address.SetHost(config.Address);
            serverThread          = new Thread(ListenLoop);
            serverThread.Name     = "Enet Server";
            serverThread.Priority = ThreadPriority.AboveNormal;
        }
Ejemplo n.º 19
0
        protected Queue <NetQItem> m_SendQueue = new Queue <NetQItem>(); // packet send queue

        /// <summary>
        /// Sends arbitrary bytes of data across the wire.  Note that if the remote endpoint can't decipher the data
        /// as a known packet, the connection will be dropped by that endpoint immediately.
        /// </summary>
        /// <param name="data">bytes to send</param>
        public virtual int Send(byte[] data, PacketFlags flags)
        {
            //Log.LogMsg("@__@ Monitor Enter");
            if (!OwningConnection.IsAlive)
            {
                return(-1);
            }

            //Log.LogMsg("==>Sending " + data.Length.ToString() + " bytes.");
            try
            {
                bool isUDP = (flags & PacketFlags.UDP) != 0;
                if (isUDP)
                {
                    if (!OwningConnection.CanSendUDP)
                    {
                        Log.LogMsg("!!! Tried sending UDP packet when the connection wasn't yet ready to send UDP. Dropping packet.");
                        return(0);
                    }

                    // Don't allow fragmenting UDP packets
                    if (data.Length > 1024)
                    {
                        Log.LogMsg("Message exceeded UDP size of 1024 bytes. Sending via TCP instead.");
                        flags &= ~PacketFlags.UDP;
                    }
                }

                lock (m_SendQueue)
                {
                    NetQItem qi = new NetQItem();
                    qi.Flags = flags;
                    qi.Data  = data;
                    qi.IsUDP = isUDP;
                    m_SendQueue.Enqueue(qi);

                    Monitor.Pulse(m_SendQueue);
                    return(1);
                }
            }
            catch (Exception sendExc)
            {
                return(-1);;
            }

            return(1);
        }
Ejemplo n.º 20
0
        public bool sendPacket(Peer peer, byte[] source, Channel channelNo, PacketFlags flag = PacketFlags.Reliable)
        {
            ////PDEBUG_LOG_LINE(Logging," Sending packet:\n");
            //if(length < 300)
            //printPacket(source, "Sent: ");
            byte[] temp;
            if (source.Length >= 8)
            {
                temp = _game.GetBlowfish().Encrypt(source);
            }
            else
            {
                temp = source;
            }

            return(peer.Send((byte)channelNo, temp));
        }
Ejemplo n.º 21
0
        public bool Send(byte[] buffer, Channel channelNo, PacketFlags flag = PacketFlags.Reliable)
        {
            if (buffer.Length >= 8)
            {
                buffer = LoLServer.BlowFish.Encrypt(buffer);
                fixed(byte *data = buffer)
                {
                    var packet = enet_packet_create(new IntPtr(data), new IntPtr(buffer.Length), flag);

                    if (enet_peer_send(Peer, (byte)channelNo, packet) < 0)
                    {
                        return(false);
                    }
                }

                return(true);
        }
Ejemplo n.º 22
0
        public void Create(byte[] data, int offset, int length, PacketFlags flags)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (offset < 0 || length < 0 || length > data.Length - offset)
            {
                throw new ArgumentOutOfRangeException();
            }

            var ptr = Marshal.AllocHGlobal(length);

            Marshal.Copy(data, offset, ptr, length);
            Create(ptr, length, flags);
            Marshal.FreeHGlobal(ptr);
        }
Ejemplo n.º 23
0
        public override void Send(List <byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
        {
            if (this.Id == 0)
            {
                throw new Exception("UChannel已经被Dispose, 不能发送消息");
            }
            int size   = buffers.Select(b => b.Length).Sum();
            var buffer = new byte[size];
            int index  = 0;

            foreach (byte[] bytes in buffers)
            {
                Array.Copy(bytes, 0, buffer, index, bytes.Length);
                index += bytes.Length;
            }
            this.socket.SendAsync(buffer, channelID, flags);
        }
Ejemplo n.º 24
0
 public void Send(uint peerId, byte[] data, byte channelId, PacketFlags flags)
 {
     try
     {
         var packet = default(Packet);
         packet.Create(data, flags);
         var peer = FindPeer(peerId);
         if (peer.IsSet)
         {
             peer.Send(channelId, ref packet);
         }
     }
     catch (Exception e)
     {
         UnityEngine.Debug.Log("ERROR Send : " + e);
     }
 }
Ejemplo n.º 25
0
        public bool BroadcastPacketVision(IGameObject o, byte[] data, Channel channelNo,
                                          PacketFlags flag = PacketFlags.Reliable)
        {
            foreach (var team in _teamsEnumerator)
            {
                if (team == TeamId.TEAM_NEUTRAL)
                {
                    continue;
                }

                if (_game.ObjectManager.TeamHasVisionOn(team, o))
                {
                    BroadcastPacketTeam(team, data, channelNo, flag);
                }
            }

            return(true);
        }
Ejemplo n.º 26
0
        public EchoClient(int id, Configuration config, BenchmarkStatistics benchmarkStatistics) : base(config)
        {
            this.id     = id;
            this.config = config;
            this.benchmarkStatistics = benchmarkStatistics;
            timeout     = Utilities.CalculateTimeout(this.config.ClientTickRate);
            packetFlags = ENetBenchmark.GetPacketFlags(config.Transmission);

            host    = new Host();
            address = new Address();
            address.SetHost(config.Address);
            address.Port = (ushort)config.Port;
            isDisposed   = false;

            listenThread              = new Thread(ListenLoop);
            listenThread.Name         = $"ENet Client {id}";
            listenThread.IsBackground = true;
        }
Ejemplo n.º 27
0
 public bool SendPacket(int userId, byte[] source, Channel channelNo, PacketFlags flag = PacketFlags.Reliable)
 {
     byte[] temp;
     if (source.Length >= 8)
     {
         temp = _blowfish.Encrypt(source);
     }
     else
     {
         temp = source;
     }
     // sometimes we want to send packets to some user but this user doesn't exist (like in broadcast when not all players connected)
     if (_peers.ContainsKey(userId))
     {
         return(_peers[userId].Send((byte)channelNo, temp));
     }
     return(false);
 }
Ejemplo n.º 28
0
        public bool BroadcastPacket(byte[] data, Channel channelNo, PacketFlags flag = PacketFlags.Reliable)
        {
            byte[] temp;
            if (data.Length >= 8)
            {
                temp = _blowfish.Encrypt(data);
            }
            else
            {
                temp = data;
            }

            var packet = new ENet.Packet();

            packet.Create(temp);
            _server.Broadcast((byte)channelNo, ref packet);
            return(true);
        }
Ejemplo n.º 29
0
        // v1.4.0b6: Mirror rearranged the ClientSend params, so we need to apply a fix for that or
        // we end up using the obsoleted version. The obsolete version isn't a fatal error, but
        // it's best to stick with the new structures.
        public override void ClientSend(ArraySegment <byte> segment, int channelId)
#endif
        {
            if (Client == null)
            {
                Debug.LogError("Client object is null, this shouldn't really happen but it did...");
                return;
            }

            if (channelId < 0 || channelId > Channels.Length)
            {
                Debug.LogError("Channel ID is out of bounds.");
                return;
            }

            // Create our struct...
            Packet clientOutgoingPacket = default;
            int    byteCount            = segment.Count;
            int    byteOffset           = segment.Offset;
            // Set our desired flags...
            PacketFlags desiredFlags = (PacketFlags)Channels[channelId];

            // Warn if over recommended MTU...
            bool flagsSet = (desiredFlags & ReliableOrUnreliableFragmented) > 0;

            if (LogType != IgnoranceLogType.Nothing && byteCount > 1200 && !flagsSet)
            {
                Debug.LogWarning($"Warning: Client trying to send a Unreliable packet bigger than the recommended ENet 1200 byte MTU ({byteCount} > 1200). ENet will force Reliable Fragmented delivery.");
            }

            // Create the packet.
            clientOutgoingPacket.Create(segment.Array, byteOffset, byteCount + byteOffset, desiredFlags);
            // byteCount

            // Enqueue the packet.
            IgnoranceOutgoingPacket dispatchPacket = new IgnoranceOutgoingPacket
            {
                Channel = (byte)channelId,
                Payload = clientOutgoingPacket
            };

            // Pass the packet onto the thread for dispatch.
            Client.Outgoing.Enqueue(dispatchPacket);
        }
Ejemplo n.º 30
0
        // v1.4.0b6: Mirror rearranged the ServerSend params, so we need to apply a fix for that or
        // we end up using the obsoleted version. The obsolete version isn't a fatal error, but
        // it's best to stick with the new structures.
        public override void ServerSend(int connectionId, ArraySegment <byte> segment, int channelId)
#endif
        {
            // Debug.Log($"ServerSend({connectionId}, {channelId}, <{segment.Count} byte segment>)");

            if (Server == null)
            {
                Debug.LogError("Cannot enqueue data packet; our Server object is null. Something has gone wrong.");
                return;
            }

            if (channelId < 0 || channelId > Channels.Length)
            {
                Debug.LogError("Channel ID is out of bounds.");
                return;
            }

            // Packet Struct
            Packet      serverOutgoingPacket = default;
            int         byteCount            = segment.Count;
            int         byteOffset           = segment.Offset;
            PacketFlags desiredFlags         = (PacketFlags)Channels[channelId];

            // Warn if over recommended MTU
            bool flagsSet = (desiredFlags & ReliableOrUnreliableFragmented) > 0;

            if (LogType != IgnoranceLogType.Nothing && byteCount > 1200 && !flagsSet)
            {
                Debug.LogWarning($"Warning: Server trying to send a Unreliable packet bigger than the recommended ENet 1200 byte MTU ({byteCount} > 1200). ENet will force Reliable Fragmented delivery.");
            }

            // Create the packet.
            serverOutgoingPacket.Create(segment.Array, byteOffset, byteCount + byteOffset, (PacketFlags)Channels[channelId]);

            // Enqueue the packet.
            IgnoranceOutgoingPacket dispatchPacket = new IgnoranceOutgoingPacket
            {
                Channel      = (byte)channelId,
                NativePeerId = (uint)connectionId - 1, // ENet's native peer ID will be ConnID - 1
                Payload      = serverOutgoingPacket
            };

            Server.Outgoing.Enqueue(dispatchPacket);
        }
Ejemplo n.º 31
0
 private void _read()
 {
     _transactionId = m_io.ReadU2be();
     _flags         = new PacketFlags(m_io, this, m_root);
     _qdcount       = m_io.ReadU2be();
     _ancount       = m_io.ReadU2be();
     _nscount       = m_io.ReadU2be();
     _arcount       = m_io.ReadU2be();
     _queries       = new List <Query>((int)(Qdcount));
     for (var i = 0; i < Qdcount; i++)
     {
         _queries.Add(new Query(m_io, this, m_root));
     }
     _answers = new List <Answer>((int)(Ancount));
     for (var i = 0; i < Ancount; i++)
     {
         _answers.Add(new Answer(m_io, this, m_root));
     }
 }
Ejemplo n.º 32
0
        public override void Send(List <byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
        {
            if (this.Id == 0)
            {
                throw new Exception("TChannel已经被Dispose, 不能发送消息");
            }
            ushort size = (ushort)buffers.Select(b => b.Length).Sum();

            byte[] sizeBuffer = BitConverter.GetBytes(size);
            this.sendBuffer.SendTo(sizeBuffer);
            foreach (byte[] buffer in buffers)
            {
                this.sendBuffer.SendTo(buffer);
            }
            if (this.isConnected)
            {
                this.StartSend();
            }
        }
        public bool broadcastPacket(byte[] data, Channel channelNo, PacketFlags flag = PacketFlags.Reliable)
        {
            ////PDEBUG_LOG_LINE(Logging," Broadcast packet:\n");
            //printPacket(data, "Broadcast: ");
            Sniffer.getInstance().Send(data, true, true);

            fixed(byte *b = data)
            {
                if (data.Length >= 8)
                {
                    BlowFishCS.BlowFishCS.Encrypt1(game.getBlowfish(), b, new IntPtr(data.Length - (data.Length % 8)));
                }

                var packet = enet_packet_create(new IntPtr(b), new IntPtr(data.Length), (PacketFlags)flag);

                enet_host_broadcast(game.getServer(), (byte)channelNo, packet);
            }

            return(true);
        }
Ejemplo n.º 34
0
        public bool broadcastPacket(byte[] data, Channel channelNo, PacketFlags flag = PacketFlags.Reliable)
        {
            ////PDEBUG_LOG_LINE(Logging," Broadcast packet:\n");
            //printPacket(data, "Broadcast: ");
            byte[] temp;
            if (data.Length >= 8)
            {
                temp = _blowfish.Encrypt(data);
            }
            else
            {
                temp = data;
            }

            var packet = new Packet();

            packet.Create(temp);
            _server.Broadcast((byte)channelNo, ref packet);
            return(true);
        }
Ejemplo n.º 35
0
        public bool broadcastPacketVision(GameObject o, byte[] data, Channel channelNo,
                                          PacketFlags flag = PacketFlags.Reliable)
        {
            var game = Program.ResolveDependency <Game>();

            foreach (var team in _teamsEnumerator)
            {
                if (team == TeamId.TEAM_NEUTRAL)
                {
                    continue;
                }

                if (game.ObjectManager.TeamHasVisionOn(team, o))
                {
                    broadcastPacketTeam(team, data, channelNo, flag);
                }
            }

            return(true);
        }
Ejemplo n.º 36
0
        public StreamingPacket(BufRefLen reader)
        {
            SendStreamId    = reader.ReadFlip32();
            ReceiveStreamId = reader.ReadFlip32();
            SequenceNumber  = reader.ReadFlip32();
            AckTrhough      = reader.ReadFlip32();

            NACKs = new List <uint>();
            var nackcount = reader.Read8();

            for (int i = 0; i < nackcount; ++i)
            {
                NACKs.Add(reader.ReadFlip32());
            }

            ResendDelay = reader.Read8();

            Flags = (PacketFlags)reader.ReadFlip16();
            var optionsize = reader.ReadFlip16();

            // Options order
            // DELAY_REQUESTED
            // FROM_INCLUDED
            if ((Flags & PacketFlags.FROM_INCLUDED) != 0)
            {
                From = new I2PDestination(reader);
            }
            // MAX_PACKET_SIZE_INCLUDED
            if ((Flags & PacketFlags.MAX_PACKET_SIZE_INCLUDED) != 0)
            {
                var mtu = reader.ReadFlip16();
            }
            // OFFLINE_SIGNATURE
            // SIGNATURE_INCLUDED
            if ((Flags & PacketFlags.SIGNATURE_INCLUDED) != 0)
            {
                Signature = new I2PSignature(reader, From.Certificate);
            }

            Payload = reader.ReadBufLen(reader.Length);
        }
Ejemplo n.º 37
0
        private E <string> AddOutgoingSplitData(ReadOnlySpan <byte> rawData, PacketType packetType, PacketFlags addFlags = PacketFlags.None)
        {
            int  pos   = 0;
            bool first = true;
            bool last;

            // TODO check if "packBuffer.FreeSlots >= packetSplit.Count"

            do
            {
                int blockSize = Math.Min(MaxOutContentSize, rawData.Length - pos);
                if (blockSize <= 0)
                {
                    break;
                }

                var flags = PacketFlags.None;
                last = pos + blockSize == rawData.Length;
                if (first ^ last)
                {
                    flags |= PacketFlags.Fragmented;
                }
                if (first)
                {
                    flags |= addFlags;
                    first  = false;
                }

                Debug.Assert(!NeedsSplitting(blockSize));
                var sendResult = SendOutgoingData(rawData.Slice(pos, blockSize), packetType, flags);
                if (!sendResult.Ok)
                {
                    return(sendResult);
                }

                pos += blockSize;
            } while (!last);

            return(R.Ok);
        }
Ejemplo n.º 38
0
 public PacketHeader(byte type, byte subtype, PacketFlags packetFlags) : this(type, subtype, (byte)packetFlags)
 {
 }
Ejemplo n.º 39
0
 private void SetFlag(PacketFlags flag)
 {
     this.Flags |= flag;
 }
Ejemplo n.º 40
0
 public void UnloadCharacter()
 {
     if (mChannel != null)
         ChannelMgr.Leave(this);
     mClientFlags = PacketFlags.Login;
     mPlace = MMatchPlace.Outside;
     mCharacter = new MTD_CharInfo();
 }
Ejemplo n.º 41
0
        public void Create(void* data, int length, PacketFlags flags)
        {
            if (_packet != null)
            {
                throw new InvalidOperationException("Already created.");
            }

            _packet = Native.enet_packet_create(data, (IntPtr) length, flags);
            if (_packet == null)
            {
                throw new ENetException(0, "Packet creation call failed.");
            }
        }
Ejemplo n.º 42
0
		internal static extern IntPtr ENetPacketCreate(byte[] data, uint dataLength, PacketFlags flags);
Ejemplo n.º 43
0
		public override void SendAsync(
				List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
		{
			int size = buffers.Select(b => b.Length).Sum();
			byte[] buffer = new byte[size];
			int index = 0;
			foreach (byte[] bytes in buffers)
			{
				Array.Copy(bytes, 0, buffer, index, bytes.Length);
				index += bytes.Length;
			}

			if (!this.isConnected)
			{
				BufferInfo info = new BufferInfo { Buffer = buffer, ChannelID = channelID, Flags = flags };
				this.queue.Enqueue(info);
				return;
			}

			this.socket.SendAsync(buffer, channelID, flags);
		}
Ejemplo n.º 44
0
 private void RemoveFlag(PacketFlags flag)
 {
     this.Flags &= ~flag;
 }
Ejemplo n.º 45
0
 public override ENetPacket* packet_create(IntPtr data, IntPtr dataLength, PacketFlags flags)
 {
     return native_packet_create(data, dataLength, flags);
 }
Ejemplo n.º 46
0
 static extern ENetPacket* native_packet_create(IntPtr data, IntPtr dataLength, PacketFlags flags);
Ejemplo n.º 47
0
		/// <summary>
		/// 发送消息
		/// </summary>
		public abstract void Send(byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
Ejemplo n.º 48
0
        /// <summary>
        /// Sends arbitrary bytes of data across the wire.  Note that if the remote endpoint can't decipher the data
        /// as a known packet, the connection will be dropped by that endpoint immediately.  
        /// </summary>
        /// <param name="data">bytes to send</param>
        public virtual int Send(byte[] data, PacketFlags flags)
        {
            //Log.LogMsg("@__@ Monitor Enter");
            if (!OwningConnection.IsAlive)
            {
                //// Log.LogMsg("Testy 3");
                return -1;
            }

            //Log.LogMsg("==>Sending " + data.Length.ToString() + " bytes.");
            try
            {
                bool isUDP = (flags & PacketFlags.UDP) != 0;

            #if SILVERLIGHT
                // Silverlight can't do UDP and it can only send Async, i.e. Non-Blocking
                isUDP = false;
                OwningConnection.BlockingMode = false;
            #endif
                if (isUDP)
                {
                    //// Log.LogMsg("Testy 4");
                    if (!OwningConnection.CanSendUDP)
                    {
                        Log.LogMsg("!!! Tried sending UDP packet when the connection wasn't yet ready to send UDP. Dropping packet.");
                        return 0;
                    }

                    // Don't allow fragmenting UDP packets
                    if (data.Length > m_SendArgsUDP.Buffer.Length && data.Length > 1024)
                    {
                        Log.LogMsg("Message exceeded UDP size. Sending via TCP instead.");
                        flags &= ~PacketFlags.UDP;
                    }
                }

                if (!OwningConnection.BlockingMode)
                {
                    // send via asyncsend, but only one send op can be in progress at one time
                    // out of order packets can happen because the actual send is done with I/O completion ports and if multiple
                    // packets get submitted to the I/O queue they could be processed out of order, especially if the packet are of wildly differing sizes
                    if (isUDP)
                    {
                        //// Log.LogMsg("Testy 5");
                        lock (m_SendQueueUDP)
                        {
                            if (1 == Interlocked.Exchange(ref m_SendingUDP, 1))
                            {
                                // failed to get the lock - a message is in progress.  queue message.
                                NetQItem qi = new NetQItem();
                                qi.Flags = flags;
                                qi.Data = data;
                                m_SendQueueUDP.Enqueue(qi);
                                Log.LogMsg("Queueing UDP packet. Now " + m_SendQueueUDP.Count.ToString() + " in Queue.");
                                return 1;
                            }
                            //Log.LogMsg("Acquired UDP send lock.");
                        }
                    }
                    else
                    {
                        lock (m_SendQueue)
                        {
                            if (1 == Interlocked.Exchange(ref m_Sending, 1))
                            {
                                // failed to get the lock - a message is in progress.  queue message.
                                NetQItem qi = new NetQItem();
                                qi.Flags = flags;
                                qi.Data = data;
                                m_SendQueue.Enqueue(qi);
                                Log.LogMsg("Queueing TCP packet. Now " + m_SendQueue.Count.ToString() + " in Queue.");
                                return 1;
                            }
                            //Log.LogMsg("Acquired TCP send lock.");
                        }
                    }
                }

                SocketAsyncEventArgs args = isUDP ? m_SendArgsUDP : m_SendArgs;
                SockState state = args.UserToken as SockState;
                state.Flags = flags;
                state.PacketBuffer = data;
                //// Log.LogMsg("Testy 6");
                SendBuffer(args, state, isUDP);
            }
            catch (Exception sendExc)
            {
                OwningConnection.KillConnection(sendExc.Message);
                return -1; ;
            }

            return 1;
        }
Ejemplo n.º 49
0
 public static extern ENetPacket* enet_packet_create(void* data, IntPtr dataLength, PacketFlags flags);
Ejemplo n.º 50
0
		public abstract void Send(List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
Ejemplo n.º 51
0
        /// <summary>
        /// Sends arbitrary bytes of data across the wire.  Note that if the remote endpoint can't decipher the data
        /// as a known packet, the connection will be dropped by that endpoint immediately.  
        /// </summary>
        /// <param name="data">bytes to send</param>
        public virtual int Send(byte[] data, PacketFlags flags)
        {
            //Log.LogMsg("@__@ Monitor Enter");
            if (!OwningConnection.IsAlive)
            {
                return -1;
            }

            //Log.LogMsg("==>Sending " + data.Length.ToString() + " bytes.");
            try
            {
                bool isUDP = (flags & PacketFlags.UDP) != 0;
                if (isUDP)
                {
                    if (!OwningConnection.CanSendUDP)
                    {
                        Log.LogMsg("!!! Tried sending UDP packet when the connection wasn't yet ready to send UDP. Dropping packet.");
                        return 0;
                    }

                    // Don't allow fragmenting UDP packets
                    if (data.Length > 1024)
                    {
                        Log.LogMsg("Message exceeded UDP size of 1024 bytes. Sending via TCP instead.");
                        flags &= ~PacketFlags.UDP;
                    }
                }

                lock (m_SendQueue)
                {
                    NetQItem qi = new NetQItem();
                    qi.Flags = flags;
                    qi.Data = data;
                    qi.IsUDP = isUDP;
                    m_SendQueue.Enqueue(qi);

                    Monitor.Pulse(m_SendQueue);
                    return 1;
                }

            }
            catch (Exception sendExc)
            {
                return -1; ;
            }

            return 1;
        }
Ejemplo n.º 52
0
 public abstract ENetPacket* packet_create(IntPtr data, IntPtr dataLength, PacketFlags flags);
Ejemplo n.º 53
0
 private bool IsFlagSet(PacketFlags flag)
 {
     return (this.Flags & flag) != 0;
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Gets the value of the specified flag.
 /// </summary>
 protected bool GetFlag(PacketFlags flag)
 {
     return (_packetFlags & flag) == flag;
 }
Ejemplo n.º 55
0
        private Packet CreatePacket(int type, int subType, PacketFlags flags, byte[] data)
        {
            Packet p = CreatePacket(type, subType, false, false);

            if (p != null)
            {
                p.Flags = flags;
                p.PacketTypeID = type;
                p.PacketSubTypeID = subType;
                //Log.LogMsg("Attempting to deserialize " + (p.IsUDP? "UDP" : "TCP") + " packet "+ p.PacketTypeID.ToString());
                p.DeSerialize(data, new Pointer());
                //Log.LogMsg("Deserialized " + (p.IsUDP? "UDP" : "TCP") + " packet " + p.GetType().ToString());
            }
            return p;
        }
Ejemplo n.º 56
0
 public static ENetPacket* enet_packet_create(IntPtr data, IntPtr dataLength, PacketFlags flags)
 {
     return Platform.packet_create(data, dataLength, flags);
 }
Ejemplo n.º 57
0
 public HandlerDelegate(PacketProcessor pAction, PacketFlags pFlags)
 {
     mProcessor = pAction;
     mFlags = pFlags;
 }
Ejemplo n.º 58
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="channelId"></param>
 /// <param name="data"></param>
 /// <param name="flags"></param>
 private void Send(byte channelId, byte[] data, PacketFlags flags)
 {
     try
     {
         m_peer.Send(channelId, data, flags);
     }
     catch(Exception e)
     {
     }
 }
Ejemplo n.º 59
0
 public void Create(byte[] data, int offset, int length, PacketFlags flags)
 {
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (offset < 0 || length < 0 || length > data.Length - offset)
     {
         throw new ArgumentOutOfRangeException();
     }
     fixed (byte* bytes = data)
     {
         Create(bytes + offset, length, flags);
     }
 }
Ejemplo n.º 60
0
		public void SendAsync(byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
		{
			if (this.PeerPtr == IntPtr.Zero)
			{
				throw new Exception($"USocket 已经被Dispose,不能发送数据!");
			}
			if (!isConnected)
			{
				sendQueue.Enqueue(new BufferInfo { Buffer = data, ChannelID = channelID, Flags = flags });
				return;
			}
			UPacket packet = new UPacket(data, flags);
			NativeMethods.ENetPeerSend(this.PeerPtr, channelID, packet.PacketPtr);
			// enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
			packet.PacketPtr = IntPtr.Zero;
		}