示例#1
0
    byte[] Serialize <T>(NetworkPacket <T> packet, uint objectId = 0, uint senderId = 0)
    {
        PacketHeader header = new PacketHeader();
        MemoryStream stream = new MemoryStream();

        header.protocolId = 0;
        header.packetType = packet.packetType;
        header.Serialize(stream);

        if (packet.packetType == (ushort)PacketType.User)
        {
            UserPacketHeader userHeader = new UserPacketHeader();
            userHeader.packetType = packet.userPacketType;
            userHeader.packetId   = currentPacketId++;
            //userHeader.senderId   = ConnectionManager.Instance.clientId;
            userHeader.senderId = senderId;
            userHeader.objectId = objectId;
            userHeader.Serialize(stream);
        }

        packet.Serialize(stream);

        stream.Close();

        return(stream.ToArray());
    }
    private byte[] SerializePacket <T>(NetworkPacket <T> networkPacket, uint senderId, uint objectId)
    {
        PacketHeader packetHeader = new PacketHeader();
        MemoryStream stream       = new MemoryStream();

        packetHeader.packetType = networkPacket.packetType;

        packetHeader.Serialize(stream);

        if ((PacketType)networkPacket.packetType == PacketType.User)
        {
            GamePacket <T>   gamePacket       = networkPacket as GamePacket <T>;
            UserPacketHeader userPacketHeader = new UserPacketHeader();

            userPacketHeader.id         = currentPacketId++;
            userPacketHeader.senderId   = senderId;
            userPacketHeader.objectId   = objectId;
            userPacketHeader.packetType = gamePacket.userPacketType;

            userPacketHeader.Serialize(stream);
        }

        networkPacket.Serialize(stream);

        stream.Close();

        return(stream.ToArray());
    }
示例#3
0
    byte[] Serialize <T>(NetworkPacket <T> packet, uint objectId)
    {
        PacketHeader     header     = new PacketHeader();
        UserPacketHeader userHeader = new UserPacketHeader();
        MemoryStream     stream     = new MemoryStream();

        header.protocolId = 0;

        header.packetType = packet.packetType;

        if (packet.packetType == PacketType.User)
        {
            userHeader.packetType = packet.userPacketType;
            userHeader.senderId   = NetworkManager.Instance.clientId;
            userHeader.objectId   = objectId;
        }

        header.Serialize(stream);
        userHeader.Serialize(stream);
        packet.Serialize(stream);

        stream.Close();

        return(stream.ToArray());
    }
    public void OnReceiveData(byte[] data, IPEndPoint iPEndPoint)
    {
        MemoryStream  memoryStream  = new MemoryStream(data);
        PacketWithCrc packetWithCrc = new PacketWithCrc();

        packetWithCrc.Deserialize(memoryStream);
        memoryStream.Close();

        if (crc32.IsDataCorrupted(packetWithCrc.data, packetWithCrc.crc))
        {
            UnityEngine.Debug.LogError("Received corrupted data from " + iPEndPoint);
            return;
        }
        memoryStream = new MemoryStream(packetWithCrc.data);
        PacketHeader packetHeader = new PacketHeader();

        packetHeader.Deserialize(memoryStream);

        if ((PacketType)packetHeader.packetTypeID == PacketType.User)
        {
            UserPacketHeader userPacketHeader = new UserPacketHeader();
            userPacketHeader.Deserialize(memoryStream);

            ReliablePacketHeader reliablePacketHeader = new ReliablePacketHeader();
            reliablePacketHeader.Deserialize(memoryStream);
            ProcessReliablePacketReceived(reliablePacketHeader);

            InvokeCallback(userPacketHeader, memoryStream);
        }
        else
        {
            NetworkManager.Instance.OnReceivePacket(iPEndPoint, (PacketType)packetHeader.packetTypeID, memoryStream);
        }
        memoryStream.Close();
    }
示例#5
0
    byte[] Serialize <T>(OrderedNetworkPacket <T> packet, uint objectId, uint id)
    {
        PacketHeader     header     = new PacketHeader();
        UserPacketHeader userHeader = new UserPacketHeader();
        MemoryStream     stream     = new MemoryStream();

        header.protocolId = 0;

        header.packetType = packet.packetType;

        if (packet.packetType == PacketType.User)
        {
            userHeader.packetType = packet.userPacketType;
            userHeader.senderId   = NetworkManager.Instance.clientId;
            userHeader.objectId   = objectId;
        }

        header.Serialize(stream);
        userHeader.Serialize(stream);
        packet.Serialize(stream, id);// igual que Serialize normal, pero se agrega un paquete con el ID

        stream.Close();

        return(stream.ToArray());
    }
 public void Reset()
 {
     reliablePacketHeader = default;
     userPacketHeader     = default;
     stream            = default;
     receptionCallback = default;
 }
 public void InvokeCallback(UserPacketHeader packetHeader, Stream stream)
 {
     if (onPacketReceived.ContainsKey(packetHeader.objectID))
     {
         onPacketReceived[packetHeader.objectID].Invoke(
             packetHeader.packetID,
             packetHeader.packetTypeID,
             stream
             );
     }
 }
    private void DeserializePacket(byte[] data, out MemoryStream stream, out PacketHeader packetHeader, ref UserPacketHeader userPacketHeader)
    {
        stream       = new MemoryStream(data);
        packetHeader = new PacketHeader();

        packetHeader.Deserialize(stream);

        if ((PacketType)packetHeader.packetType == PacketType.User)
        {
            userPacketHeader = new UserPacketHeader();
            userPacketHeader.Deserialize(stream);
        }
    }
    public byte[] SerializePacket <T>(NetworkPacket <T> networkPacket, uint senderID = 0, uint objectID = 0,
                                      ReliablePacketHeader reliablePacketHeader      = null)
    {
        byte[] data = null;

        PacketWrapper packetWrapper = new PacketWrapper();
        MemoryStream  memoryStream  = new MemoryStream();
        PacketHeader  packetHeader  = new PacketHeader();

        packetHeader.ProtocolID      = ProtocolID;
        packetHeader.PacketTypeIndex = networkPacket.PacketTypeIndex;

        packetHeader.Serialize(memoryStream);

        if ((PacketType)networkPacket.PacketTypeIndex == PacketType.User)
        {
            UserNetworkPacket <T> userNetworkPacket = networkPacket as UserNetworkPacket <T>;
            UserPacketHeader      userPacketHeader  = new UserPacketHeader();

            userPacketHeader.UserPacketTypeIndex = userNetworkPacket.UserPacketTypeIndex;
            userPacketHeader.SenderID            = senderID;
            userPacketHeader.ObjectID            = objectID;
            userPacketHeader.Reliable            = (reliablePacketHeader != null);

            userPacketHeader.Serialize(memoryStream);

            if (reliablePacketHeader != null)
            {
                reliablePacketHeader.Serialize(memoryStream);
            }
        }

        networkPacket.Serialize(memoryStream);
        memoryStream.Close();

        data = memoryStream.ToArray();

        packetWrapper.Crc        = crcCalculator.ComputeCrc32(data);
        packetWrapper.PacketData = data;

        memoryStream = new MemoryStream();

        packetWrapper.Serialize(memoryStream);
        memoryStream.Close();

        data = memoryStream.ToArray();

        return(data);
    }
    public void OnReceiveData(byte[] data, IPEndPoint ipEndpoint)
    {
        Debug.Log($"Receiving: " + data);

        PacketHeader     packetHeader     = new PacketHeader();
        UserPacketHeader userPacketHeader = new UserPacketHeader();
        MemoryStream     stream           = new MemoryStream(data);

        DeserializePacket(data, out stream, out packetHeader, ref userPacketHeader);

        if (userPacketHeader != null)
        {
            InvokeCallback(userPacketHeader.objectId, userPacketHeader.packetType, userPacketHeader.senderId, stream);
        }

        stream.Close();
    }
    public void ReceiveData(byte[] data, IPEndPoint ipEndPoint)
    {
        MemoryStream         memoryStream         = null;
        PacketHeader         packetHeader         = null;
        UserPacketHeader     userPacketHeader     = null;
        ReliablePacketHeader reliablePacketHeader = null;

        if (DeserializePacket(data, out memoryStream, out packetHeader, ref userPacketHeader, ref reliablePacketHeader))
        {
            if (packetHeader.ProtocolID == ProtocolID)
            {
                if (userPacketHeader != null)
                {
                    if (userPacketHeader.Reliable)
                    {
                        Action <ushort, uint, Stream> processCallback = GetPacketReceptionCallback(userPacketHeader.ObjectID);
                        PacketReliabilityManager.Instance.ProcessReceivedStream(memoryStream,
                                                                                userPacketHeader,
                                                                                reliablePacketHeader,
                                                                                processCallback);
                    }
                    else
                    {
                        InvokeReceptionCallback(userPacketHeader.ObjectID, userPacketHeader.UserPacketTypeIndex,
                                                userPacketHeader.SenderID, memoryStream);
                    }
                }
                else
                {
                    systemPacketReceptionCallback?.Invoke(packetHeader.PacketTypeIndex, ipEndPoint, memoryStream);
                }

                if (userPacketHeader == null || !userPacketHeader.Reliable)
                {
                    memoryStream.Close();
                }
            }
        }
    }
    public void ProcessReceivedStream(Stream stream, UserPacketHeader userPacketHeader, ReliablePacketHeader reliablePacketHeader,
                                      Action <ushort, uint, Stream> processCallback)
    {
        uint senderID = (UdpNetworkManager.Instance.IsServer) ? userPacketHeader.SenderID : 0;

        if (reliablePacketHeader.PacketID >= nextExpectedIDs[senderID])
        {
            if (reliablePacketHeader.PacketID > acknowledges[senderID])
            {
                acknowledges[senderID] = reliablePacketHeader.PacketID;
            }
            receivedPacketIDs[senderID][reliablePacketHeader.PacketID % AckBitsCount] = reliablePacketHeader.PacketID;
            UpdateAcknowledgeBits(senderID);

            int packetIndex = reliablePacketHeader.PacketID % AckBitsCount;

            packetsPendingProcess[senderID][packetIndex].reliablePacketHeader = reliablePacketHeader;
            packetsPendingProcess[senderID][packetIndex].userPacketHeader     = userPacketHeader;
            packetsPendingProcess[senderID][packetIndex].stream            = stream;
            packetsPendingProcess[senderID][packetIndex].receptionCallback = processCallback;

            if (reliablePacketHeader.PacketID == nextExpectedIDs[senderID])
            {
                while (packetsPendingProcess[senderID][packetIndex].stream != null)
                {
                    processCallback(packetsPendingProcess[senderID][packetIndex].userPacketHeader.UserPacketTypeIndex,
                                    packetsPendingProcess[senderID][packetIndex].userPacketHeader.SenderID,
                                    packetsPendingProcess[senderID][packetIndex].stream);
                    packetsPendingProcess[senderID][packetIndex].stream.Close();
                    packetsPendingProcess[senderID][packetIndex].Reset();
                    packetIndex = (packetIndex + 1) % AckBitsCount;
                    nextExpectedIDs[senderID]++;
                }
            }

            ProcessReceivedAcknowledgeInfo(reliablePacketHeader, senderID);
        }
    }
示例#13
0
    public void OnReceiveData(byte[] data, IPEndPoint endPoint)
    {
        // Debug.Log("data received" + endPoint);
        PacketHeader header       = new PacketHeader();
        MemoryStream memoryStream = new MemoryStream(data);

        header.Deserialize(memoryStream);

        Debug.Log("Deserialize: " + header.type);

        if (header.type == PacketType.User) // El packetype no es el correcto
        {
            Debug.Log("TyperHeaderAccepted");
            UserPacketHeader userHeader = new UserPacketHeader();
            userHeader.Deserialize(memoryStream);
            ReceivingPacket.Invoke(userHeader.objectId, userHeader.userType, memoryStream);
        }
        else
        {
            ReceivingInternalPacket.Invoke(header.type, memoryStream, endPoint);
        }
        memoryStream.Close();
    }
    bool DeserializePacket(byte[] data, out MemoryStream memoryStream, out PacketHeader packetHeader,
                           ref UserPacketHeader userPacketHeader, ref ReliablePacketHeader reliablePacketHeader)
    {
        bool isFaultless;

        PacketWrapper packetWrapper = new PacketWrapper();

        memoryStream = new MemoryStream(data);
        packetHeader = new PacketHeader();

        packetWrapper.Deserialize(memoryStream);

        memoryStream.Close();

        isFaultless = crcCalculator.PerformCrcCheck(packetWrapper.PacketData, packetWrapper.Crc);

        if (isFaultless)
        {
            memoryStream = new MemoryStream(packetWrapper.PacketData);

            packetHeader.Deserialize(memoryStream);

            if ((PacketType)packetHeader.PacketTypeIndex == PacketType.User)
            {
                userPacketHeader = new UserPacketHeader();
                userPacketHeader.Deserialize(memoryStream);

                if (userPacketHeader.Reliable)
                {
                    reliablePacketHeader = new ReliablePacketHeader();
                    reliablePacketHeader.Deserialize(memoryStream);
                }
            }
        }

        return(isFaultless);
    }
示例#15
0
    private byte[] Serialize(SerializablePacket packet, int objectId = 0)
    {
        PacketHeader header       = new PacketHeader();
        MemoryStream memoryStream = new MemoryStream();

        header.protocolId = currentPacketId;
        header.type       = packet.packetType;
        header.Serialize(memoryStream);

        Debug.Log("Serialize: " + header.type);

        if (header.type == PacketType.User)
        {
            UserPacketHeader userHeader = new UserPacketHeader();
            userHeader.id       = currentPacketId;
            userHeader.clientId = NetworkManager.Instance.clientId;
            userHeader.objectId = objectId;
            userHeader.userType = packet.userType;
            userHeader.Serialize(memoryStream);
        }
        packet.Serialize(memoryStream);
        memoryStream.Close();
        return(memoryStream.ToArray());
    }
示例#16
0
    public void OnReceiveData(byte[] data, IPEndPoint ipEndpoint)
    {
        PacketHeader header = new PacketHeader();
        MemoryStream stream = new MemoryStream(data);

        header.Deserialize(stream);

        if ((PacketType)header.packetType == PacketType.User)
        {
            UserPacketHeader userHeader = new UserPacketHeader();
            userHeader.Deserialize(stream);

            if (userHeader.senderId != ConnectionManager.Instance.clientId && onGamePacketReceived.ContainsKey(userHeader.objectId))
            {
                onGamePacketReceived[userHeader.objectId].Invoke(userHeader.packetId, userHeader.packetType, stream);
            }
        }
        else
        {
            onInternalPacketReceived.Invoke(header.packetType, ipEndpoint, stream);
        }

        stream.Close();
    }
    public byte[] SerializePacket <T>(NetworkPacket <T> packetToSerialize, bool isReliable = false, uint objectID = 0)
    {
        MemoryStream memoryStream = new MemoryStream();
        PacketHeader packetHeader = new PacketHeader();

        packetHeader.packetTypeID = (uint)packetToSerialize.type;
        packetHeader.Serialize(memoryStream);

        if (packetToSerialize.type == PacketType.User)
        {
            UserPacketHeader userPacketHeader = new UserPacketHeader();

            userPacketHeader.packetTypeID = packetToSerialize.userPacketTypeID;
            userPacketHeader.packetID     = localSequence;
            userPacketHeader.senderID     = NetworkManager.Instance.clientID;
            userPacketHeader.objectID     = objectID;
            userPacketHeader.isReliable   = isReliable;

            userPacketHeader.Serialize(memoryStream);


            ReliablePacketHeader reliablePacketHeader = new ReliablePacketHeader();

            reliablePacketHeader.sequence = localSequence;
            reliablePacketHeader.ack      = remoteSequence;

            //UnityEngine.Debug.Log("Setting up ackbits for packet Nro." + localSequence);
            ackBitfields = 0;
            for (int i = 0; i <= numberOfBitsInAck; i++)
            {
                if (sequenceNumbersReceived.Contains((uint)(remoteSequence - i)))
                {
                    //UnityEngine.Debug.Log("Sequence number is contained: " + (int)(expectedSequence - i));
                    ackBitfields |= 1 << i;
                }
            }
            //UnityEngine.Debug.Log("Ackbits to send: " + Convert.ToString(ackBitfields, 2));
            reliablePacketHeader.ackBitfield = ackBitfields;

            reliablePacketHeader.Serialize(memoryStream);
        }
        packetToSerialize.Serialize(memoryStream);

        PacketWithCrc packetWithCrc = new PacketWithCrc();

        packetWithCrc.crc        = crc32.CalculateCrc(memoryStream.ToArray());
        packetWithCrc.byteLength = memoryStream.ToArray().Length;
        packetWithCrc.data       = memoryStream.ToArray();
        memoryStream.Close();

        memoryStream = new MemoryStream();
        packetWithCrc.Serialize(memoryStream);
        memoryStream.Close();

        if (isReliable)
        {
            if (!packetsPendingToBeAcked.ContainsKey(localSequence))
            {
                packetsPendingToBeAcked.Add(localSequence, memoryStream.ToArray());
            }
        }

        return(memoryStream.ToArray());
    }
示例#18
0
    public void OnReceiveData(byte[] data, IPEndPoint ipEndpoint)
    {
        PacketHeader header = new PacketHeader();//CheckSum: header para leer
        MemoryStream stream = new MemoryStream(data);

        BinaryReader binaryReader = new BinaryReader(stream);

        int hash32 = binaryReader.ReadInt32(); //CheckSum: Se copia solamente el hash para verificar checksum

        byte[] dataWithoutHash = new byte[data.Length - 4];
        Array.Copy(data, 4, dataWithoutHash, 0, data.Length - 4);

        if (testCheckSum)
        {
            if (UnityEngine.Random.Range(0f, 100f) < 1f)
            {
                for (int i = 0; i < dataWithoutHash.Length; i++)//CheckSum: trucheo la copia local para que de mal y salte checksum
                {
                    if (dataWithoutHash[i] != 0)
                    {
                        dataWithoutHash[i] = 0;
                    }
                }
            }
        }
        int ourHash;

        using (MD5 md5Hash = MD5.Create())
        {
            byte[]       hash       = md5Hash.ComputeHash(dataWithoutHash);
            MemoryStream hashStream = new MemoryStream(hash);
            BinaryReader hashReader = new BinaryReader(hashStream);
            ourHash = hashReader.ReadInt32();
            hashStream.Close(); //CheckSum: creo un hash igual y tienen que ser iguales para saber que el paquete no esta corrupto
        }

        if (hash32 == ourHash)//CheckSum: verifica si son iguales
        {
            bool reliability = binaryReader.ReadBoolean();

            if (reliability)
            {
                if (testReliable)
                {
                    if (Input.GetKey(KeyCode.A))
                    {
                        stream.Close();
                        return;
                    }
                }

                uint packageAcknowledge = binaryReader.ReadUInt32();//Si es reliability lee el ack del paquete
                //este es el que recibo del otro

                if (ConnectionManager.Instance.isServer)
                {
                    Client client = ConnectionManager.Instance.clients[ConnectionManager.Instance.ipToId[ipEndpoint]];
                    client.acknowledgeChecker.RegisterPackageReceived(packageAcknowledge);
                }
                else
                {
                    ConnectionManager.Instance.client.acknowledgeChecker.RegisterPackageReceived(packageAcknowledge);
                }

                bool hasAcknowledge = binaryReader.ReadBoolean();// el bool que verifica si habia ack
                if (hasAcknowledge)
                {
                    uint lastAcknowledge      = binaryReader.ReadUInt32(); // el ultimo que llego siendo confirmado
                    uint prevAcknowledgeArray = binaryReader.ReadUInt32(); // el resto del array para verificar posicion en el mismo

                    if (ConnectionManager.Instance.isServer)
                    {
                        Client client = ConnectionManager.Instance.clients[ConnectionManager.Instance.ipToId[ipEndpoint]];
                        client.acknowledgeChecker.RegisterPackageReceived(packageAcknowledge);
                        client.acknowledgeChecker.ClearPackets(lastAcknowledge, prevAcknowledgeArray);// limpio los que ya llegaron para que los deje de spamear
                    }
                    else
                    {
                        ConnectionManager.Instance.client.acknowledgeChecker.RegisterPackageReceived(packageAcknowledge);
                        ConnectionManager.Instance.client.acknowledgeChecker.ClearPackets(lastAcknowledge, prevAcknowledgeArray);
                    }
                }
            }

            header.Deserialize(stream);

            if (header.packetType == PacketType.User)
            {
                while (stream.Length - stream.Position > 0)
                {
                    UserPacketHeader userHeader = new UserPacketHeader();
                    userHeader.Deserialize(stream);
                    InvokeCallback(userHeader.objectId, userHeader.packetType, stream);
                }
            }
            else
            {
                ConnectionManager.Instance.OnReceivePacket(ipEndpoint, header.packetType, stream);
            }
        }

        stream.Close();
    }
示例#19
0
    public void OnReceiveData(byte[] data, IPEndPoint ipEndpoint)
    {
        PacketHeader header = new PacketHeader();
        MemoryStream stream = new MemoryStream(data);

        BinaryReader binaryReader = new BinaryReader(stream);

        int hash32 = binaryReader.ReadInt32();

        byte[] dataWithoutHash = new byte[data.Length - 4];
        Array.Copy(data, 4, dataWithoutHash, 0, data.Length - 4);

#if DEBUG_CHECKSUM
        if (UnityEngine.Random.Range(0f, 100f) < 0.5f)
        {
            if (dataWithoutHash[0] != 0)
            {
                dataWithoutHash[0] = 0;
            }
            else
            {
                dataWithoutHash[0] = 1;
            }
        }
#endif
        int ourHash;
        using (MD5 md5Hash = MD5.Create()) {
            byte[]       hash       = md5Hash.ComputeHash(dataWithoutHash);
            MemoryStream hashStream = new MemoryStream(hash);
            BinaryReader hashReader = new BinaryReader(hashStream);
            ourHash = hashReader.ReadInt32();
            hashStream.Close();
        }

        if (hash32 == ourHash)
        {
            bool reliability = binaryReader.ReadBoolean();

            if (reliability)
            {
#if DEBUG_RELIABLE
                if (UnityEngine.Random.Range(0f, 100f) < 0.6f)
                {
                    // if (Input.GetKey(KeyCode.A)) {
                    stream.Close();
                    return;
                }
#endif
                uint packageAck = binaryReader.ReadUInt32();
                if (ConnectionManager.Instance.isServer)
                {
                    Client client = ConnectionManager.Instance.clients[ConnectionManager.Instance.ipToId[ipEndpoint]];
                    client.ackChecker.RegisterPackageReceived(packageAck);
                }
                else
                {
                    ConnectionManager.Instance.OwnClient.ackChecker.RegisterPackageReceived(packageAck);
                }

                bool hasAck = binaryReader.ReadBoolean();
                if (hasAck)
                {
                    uint lastAck      = binaryReader.ReadUInt32();
                    uint prevAckArray = binaryReader.ReadUInt32();

                    if (ConnectionManager.Instance.isServer)
                    {
                        Client client = ConnectionManager.Instance.clients[ConnectionManager.Instance.ipToId[ipEndpoint]];
                        client.ackChecker.ClearPackets(lastAck, prevAckArray);
                    }
                    else
                    {
                        ConnectionManager.Instance.OwnClient.ackChecker.ClearPackets(lastAck, prevAckArray);
                    }
                }
            }

            header.Deserialize(stream);

            if (header.packetType == PacketType.User)
            {
                while (stream.Length - stream.Position > 0)
                {
                    UserPacketHeader userHeader = new UserPacketHeader();
                    userHeader.Deserialize(stream);
                    InvokeCallback(userHeader.objectId, userHeader.packetType, stream);
                }
            }
            else
            {
                ConnectionManager.Instance.OnReceivePacket(ipEndpoint, header.packetType, stream);
            }
        }
        else
        {
            Debug.LogWarning("PACKAGE CORRUPTED");
        }

        stream.Close();
    }